Skip to content

Add TLS to Redis session storage - #6731

Merged
peppescg merged 2 commits into
stacklok:mainfrom
Sanskarzz:feat/tls-redis-session
Oct 9, 2026
Merged

peppescg merged 2 commits into
stacklok:mainfrom
Sanskarzz:feat/tls-redis-session

Conversation

@Sanskarzz

@Sanskarzz Sanskarzz commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Redis session storage configuration currently cannot enable TLS, even though the shared redisconn library supports it. This prevents standalone vMCP and proxy runtimes from connecting to Redis endpoints that require TLS. Redis-backed rate limiting creates a separate client and needs the same settings.

  • Add a shared runtime TLS configuration used by vMCP sessions, proxy sessions, and their Redis rate limiters.
  • Preserve plaintext when tls is omitted; tls: {} enables certificate and hostname verification using system roots.
  • Support private CAs through a PEM file, and return errors for missing, empty, or malformed configured CA bundles without falling back to plaintext or system roots.
  • Reuse redisconn.NewClient for the rate limiter and share CA loading with the embedded auth server while preserving its existing snake_case configuration.
  • Update runtime documentation, deep-copy code, generated schemas, and the Go SDK contract.

Partially addresses #6730. This is the runtime prerequisite; the Kubernetes API fields, CA Secret projection, and rollout handling will follow in PR B. Keep the issue open until that integration is merged.

TLS support for the operator-wide defaultRedis fallback is outside the scope of both PR A and PR B and will be tracked in a separate follow-up issue.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Focused unit tests through a temporary Taskfile using the repository's race detector, linker flags, and gotestfmt configuration; verify PR A independently of the operator changes.
  • SDK tests (task sdk-test).
  • Linting (task lint-fix, previously run on the complete implementation).
  • Regenerate manifests and API reference documentation (task operator-manifests, task crdref-gen --force) against PR A alone and compare with the staged artifacts.
  • E2E tests (task test-e2e).

Coverage includes:

  • Nil TLS versus an explicitly empty TLS object, JSON/YAML round trips, and rejection of TLS with non-Redis vMCP session storage.
  • CA loading failures for missing, empty, and malformed bundles.
  • Real TLS handshakes against a TLS-only miniredis endpoint, successful session create/load operations, password authentication, and rate-limit decisions.
  • Certificate rejection without the required private CA and errors for missing configured CA files.
  • Propagation from proxy session settings into middleware parameters and from vMCP settings into the rate-limit factory.
  • Existing proxy command and operator controller/converter tests against the runtime-only patch.

The full repository unit run previously hit a failure in TestPush/key_push_forwards_signing_capability in the plugin client package; that package passed on an isolated rerun. The full repository suite is not claimed as green here. Runner coverage does not execute the full Runner.Run lifecycle against TLS Redis, and no live Kubernetes workload connection is included in this PR.

API Compatibility

  • This PR does not break the v1beta1 API.

The optional nested VirtualMCPServer.spec.config.sessionStorage.tls schema additions are generated from the embedded runtime configuration, in both served versions. They keep generated artifacts aligned with the runtime type; top-level spec.sessionStorage.tls and Secret references belong to PR B. Existing omitted TLS settings preserve plaintext behavior.

Changes

File or area Change
pkg/redisconfig/tls.go Shared serializable TLS configuration and CA loading/validation.
pkg/authserver/runner/embeddedauthserver.go Convert the existing auth-server TLS configuration through the shared loader, retaining its public field names.
pkg/vmcp/config/config.go, validator.go Optional session TLS field and provider validation.
pkg/vmcp/server/server.go Load TLS settings before constructing Redis session data storage.
pkg/runner/config.go, runner.go, middleware.go Preserve TLS through proxy run configuration, session storage, and middleware parameters.
pkg/ratelimit/middleware.go Use the shared Redis client builder and pass TLS into the independent limiter client.
pkg/vmcp/ratelimit/factory/limiter.go Forward vMCP session TLS settings to the limiter factory.
Runtime tests and test/helpers/redistls/redistls.go TLS endpoint fixture, failure cases, storage/limiter behavior, and config propagation.
cmd/vmcp/README.md Standalone YAML configuration and trust behavior.
Generated deep-copy, VirtualMCPServer CRDs, and API reference Preserve the new pointer and document the runtime schema.
docs/server/*, sdk/go/openapi.*, sdk/go/client/oas_*_gen.go, sdk/go/client/client_test.go Publish the optional runtime TLS schema and update its deliberate contract count.

Does this introduce a user-facing change?

Yes. Standalone thv vmcp serve --config ... and vmcp serve --config ... accept:

sessionStorage:
  provider: redis
  address: redis.example.com:6379
  tls: {}

For a private CA, set tls.caCertFile to a readable PEM bundle in the runtime filesystem. Proxy run configurations receive the same optional TLS object under their existing session Redis settings. No new CLI flag is introduced.

Implementation plan

Implementation plan
  1. Introduce a neutral runtime TLS type with nil/empty semantics and shared CA loading.
  2. Wire it into both session storage runtimes and their independent Redis rate limiters.
  3. Preserve the embedded auth server's existing serialized format while reusing loading logic.
  4. Verify TLS handshakes, config propagation, provider validation, and plaintext compatibility through existing tests.
  5. Regenerate affected schemas, documentation, deep-copy code, and SDK artifacts.
  6. Deliver Kubernetes Secret references, projection, and rollout handling in PR B after this prerequisite.

Special notes for reviewers

  • A custom CA bundle replaces system roots for this Redis connection.
  • CA material is loaded at client startup; there is no certificate reload. Restart clients after changing CA file contents.
  • Explicitly configuring an empty CA file now also fails for the embedded auth server. Previously empty bytes could select system roots; public auth-server configuration field names are unchanged.
  • insecureSkipVerify is an explicit opt-in that disables certificate and hostname verification.
  • Sessions and rate limiting share settings and client construction, but retain separate clients and existing cleanup ownership.
  • Kubernetes top-level TLS fields and CA Secret mounts are deferred to PR B. TLS for the operator-wide defaultRedis fallback is a separate follow-up.
  • The production change is 10 source files and 133 changed lines; tests, docs, and generated artifacts account for the larger total diff.

@codecov

codecov Bot commented Sep 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.84615% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.28%. Comparing base (47dbcab) to head (5bda236).

Files with missing lines Patch % Lines
pkg/runner/runner.go 0.00% 4 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #6731   +/-   ##
=======================================
  Coverage   79.28%   79.28%           
=======================================
  Files         802      804    +2     
  Lines       81218    81271   +53     
=======================================
+ Hits        64395    64439   +44     
- Misses      16818    16827    +9     
  Partials        5        5           

☔ 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.

@peppescg peppescg 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.

Thanks a lot @Sanskarzz, this is a really solid piece of work! 🙌

@peppescg
peppescg merged commit 183978d into stacklok:main Oct 9, 2026
45 checks passed
peppescg added a commit that referenced this pull request Oct 12, 2026
* Move Redis TLS test fixture to testkit

Shared test fixtures live under test/testkit. Move the redistls
helper added for Redis session storage TLS there and update its
importers; the fixture itself is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

* Warn when Redis session storage lacks TLS

Session storage now supports TLS, but omitting it keeps the previous
plaintext connection so existing deployments are unaffected. Make
that choice visible: when a Redis password is configured, the proxy
runner and vMCP session stores log one startup WARN if TLS is not
set or certificate verification is disabled. The connection is still
allowed and the password is never logged.

The message also notes that the operator-wide default Redis
(TOOLHIVE_DEFAULT_REDIS_ADDR) cannot enable TLS yet. The rate
limiter always shares these settings, so it does not warn again.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

* Add session storage TLS to the operator

#6731 lets the proxy runner and vMCP connect to Redis session
storage over TLS, but only through hand-written RunConfig or vMCP
YAML. Operator-managed workloads had no way to request it.

Add spec.sessionStorage.tls to MCPServer, MCPRemoteProxy and
VirtualMCPServer. It reuses the existing RedisTLSConfig type from
the embedded auth server's Redis storage:

- An empty object verifies the server certificate against the
  system roots.
- caCertSecretRef mounts a private CA from a Secret at
  /etc/toolhive/session-redis-tls/ca.crt, read-only and via
  subPath, as for the auth server's Redis CA.
- insecureSkipVerify disables verification, for testing only.

The operator writes these settings into the RunConfig
(scaling_config.session_redis.tls) and the vMCP config
(sessionStorage.tls). On VirtualMCPServer the operator value replaces
any spec.config.sessionStorage.tls, like the other session storage
fields. Switching the referenced CA Secret rolls the Deployment.

CEL rules on SessionStorageConfig reject tls with a non-redis
provider, and insecureSkipVerify combined with caCertSecretRef. They
sit on SessionStorageConfig rather than on the shared type so
existing auth server resources are unaffected. The shared
insecureSkipVerify description now recommends caCertSecretRef
instead.

Refs #6730

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

* Extend Redis session storage TLS tests

Add coverage for the Redis session storage TLS paths that were not
exercised end to end:

- Runner.Run test showing the session store client takes its TLS
  settings from the RunConfig. Without TLS it does not handshake. With
  TLS, the server certificate and the hostname from the configured
  address are verified. A trusted CA connects.
- The rate limiter and the vMCP limiter factory now also cover the
  omitted-TLS case against a TLS-only server, and match the
  certificate-verification error precisely.
- An e2e spec that runs standalone vMCP against a TLS-only,
  password-protected Redis container. It opens a session and checks
  over TLS that the session was stored.

The redistls fixture gains on-disk certificates with an IP-only server
certificate. A real Redis server uses them, and they make a hostname
mismatch observable.

Refs #6730

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

* Make e2e Redis TLS certificates readable

The TLS-only Redis e2e spec bind-mounts a generated CA, certificate and
key into the Redis container. Only the key was made world-readable, so
on Linux hosts, where the container's redis user does not own the
mounted files, Redis could not read the 0600 certificate and CA, failed
to configure TLS and exited before answering PING. Docker Desktop on
macOS does not enforce file ownership on bind mounts, which hid this
locally.

Make all three files readable inside the private test directory.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

* Address review findings on session Redis TLS

The session storage CA drift check compared the live Deployment with
the raw desired volume. On an MCPRemoteProxy whose podTemplateSpec
patches that volume, every reconcile saw drift and issued a no-op
update. The check now compares live volumes with the desired ones, and
the remote proxy uses the rebuilt, patched Deployment when a
podTemplateSpec is set.

Reject configurations that would silently misbehave:

- spec.config.sessionStorage.tls on a VirtualMCPServer was accepted
  but discarded by the converter, leaving the connection plaintext.
- A caCertSecretRef with an empty name or key passed admission but
  produced a volume the Deployment API rejects on every reconcile.

The insecure-transport warning moves into the Redis session store
constructors so every caller gets it, and it now also fires without a
password because session data still crosses the network in plaintext.
Its text no longer names configuration keys that only apply to some
callers.

Also share one Secret-file volume helper between the session store and
the embedded auth server's Redis CAs, build the redistls fixture on a
single certificate generator, and drop a runner test case that only
exercised crypto/tls and go-redis.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

* Set fosite strategies that default lazily

fosite's GetAudienceStrategy and GetJWKSFetcherStrategy assign their
default to the shared Config on first use. The embedded auth server
left both unset, so concurrent token requests raced on that write. The
race detector flagged it in the pkg/authserver integration tests, which
fail on main as well.

Set both to fosite's defaults when building the Config, as is already
done for the scope strategy and secrets hasher. Behavior is unchanged;
the getters simply no longer write.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

* Fail closed on remote client key sets

The previous commit set fosite's JWKS fetcher to its default to avoid a
lazy write to the shared Config. That fetcher is never used: DCR rejects
jwks_uri for private_key_jwt and storage drops it, so client keys are
always inline. Creating it eagerly only started a ristretto cache with
goroutines that are never closed, for every auth server instance.

Use a fetcher that rejects the client instead. It still keeps fosite's
getter from writing, starts nothing, and fails closed rather than
fetching an arbitrary URL with an unhardened client if a client with a
jwks_uri ever reached client authentication.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

* Check session TLS rules on every kind and version

The sessionStorage.tls CEL rules live on the shared SessionStorageConfig
type, but admission tests only covered VirtualMCPServer at v1beta1. A
schema change could drop a rule from one kind or one served version
without any test noticing.

Run one shared table of TLS admission cases against MCPServer,
MCPRemoteProxy and VirtualMCPServer at both v1beta1 and v1alpha1.

Also document that workloads using the operator-wide defaultRedis
fallback always log the plaintext warning, and that vMCP's
no-authentication warning is separate from it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Giuseppe Scuglia <[email protected]>

---------

Signed-off-by: Giuseppe Scuglia <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants