Skip to content

feat(router): add TLS support for NATS event source - #2749

Merged
dkorittki merged 15 commits into
wundergraph:mainfrom
vatsalpatel:feat/nats-tls
Apr 23, 2026
Merged

dkorittki merged 15 commits into
wundergraph:mainfrom
vatsalpatel:feat/nats-tls

Conversation

@vatsalpatel

@vatsalpatel vatsalpatel commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Add a tls block to NatsEventSource supporting four modes: no TLS (omit block), skip verify, custom CA (1-way TLS), and mTLS.

  • New NatsTLSConfiguration struct with insecure_skip_verify, ca_file, cert_file, and key_file fields
  • TLS option building in buildNatsOptions via nats.Secure(tlsCfg); cert/key pair validated together, missing CA file surfaced at startup
  • config.schema.json updated with tls object (additionalProperties: false)
  • Golden fixture updated
  • Tests for all modes and error paths in both config_events_nats_test.go and provider_builder_test.go

Closes #2582

Summary by CodeRabbit

  • New Features

    • Added optional TLS support for NATS event providers: skip-server-cert verification, custom CA, and mutual TLS (client cert/key). Schema and sample config updated.
  • Tests

    • Added unit tests for TLS success and failure cases, covering validation for missing/mismatched fields and unknown attributes.
  • Documentation

    • Updated NATS provider docs with TLS reference, usage examples for modes, and a warning about disabling certificate verification.

Checklist

  Add a \`tls\` block to \`NatsEventSource\` supporting four modes: no TLS
  (omit block), skip verify, custom CA (1-way TLS), and mTLS.

  - New \`NatsTLSConfiguration\` struct with \`insecure_skip_verify\`,
    \`ca_file\`, \`cert_file\`, and \`key_file\` fields
  - TLS option building in \`buildNatsOptions\` via \`nats.Secure(tlsCfg)\`;
    cert/key pair validated together, missing CA file surfaced at startup
  - \`config.schema.json\` updated with \`tls\` object
    (\`additionalProperties: false\`)
  - Golden fixture updated
  - Tests for all modes and error paths in both \`config_events_nats_test.go\`
    and \`provider_builder_test.go\`

  Closes wundergraph#2582
# Conflicts:
#	router/pkg/config/config.go
#	router/pkg/config/config.schema.json
#	router/pkg/config/testdata/config_full.json
@coderabbitai

coderabbitai Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds TLS support for NATS event sources: new NatsTLSConfiguration and optional TLS on NatsEventSource; JSON schema and testdata updates; TLS option construction in NATS provider builder (skip-verify, custom CA, mTLS) with unit tests and documentation updates.

Changes

Cohort / File(s) Summary
Config types & schema
router/pkg/config/config.go, router/pkg/config/config.schema.json
Added NatsTLSConfiguration (insecure_skip_verify, ca_file, cert_file, key_file) and TLS *NatsTLSConfiguration on NatsEventSource. Extended JSON schema with events.providers.nats[].tls object (no additionalProperties) and mutual dependency rules for cert_file↔key_file.
Config tests & fixtures
router/pkg/config/config_events_nats_test.go, router/pkg/config/testdata/config_full.json
Added tests validating TLS schema handling (valid: skip-verify, CA+mTLS; invalid: missing cert/key counterpart, unknown TLS field). Updated testdata to include "TLS": null for NATS providers.
NATS provider TLS implementation
router/pkg/pubsub/nats/provider_builder.go
buildNatsOptions conditionally builds a tls.Config when eventSource.TLS is non-nil: applies InsecureSkipVerify, optionally loads CA into RootCAs, validates/loads client cert+key for mTLS, and appends nats.Secure(tlsCfg); returns errors for unreadable or misconfigured files.
NATS provider TLS tests
router/pkg/pubsub/nats/provider_builder_test.go
Added TestBuildNatsOptionsWithTLS covering success cases (skip-verify, CA-only, mTLS) and failure cases (missing/unreadable CA, only cert or only key). Added helpers to generate temporary PEM files for tests.
Docs
docs-website/router/configuration.mdx
Documented new tls block for NATS provider, described supported TLS modes (no TLS, skip-verify, custom CA, mTLS), added YAML examples and a warning about insecure_skip_verify.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(router): add TLS support for NATS event source' directly and clearly summarizes the main change in the PR.
Linked Issues check ✅ Passed All core coding requirements from issue #2582 are met: NatsTLSConfiguration struct added, TLS field added to NatsEventSource, buildNatsOptions implements TLS with nats.Secure(), config.schema.json updated with tls object and mutual cert/key constraints, golden fixture updated, comprehensive tests added.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing TLS support for NATS: config struct/schema updates, provider builder TLS logic, comprehensive tests, and documentation. No unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@vatsalpatel

Copy link
Copy Markdown
Contributor Author

Docs PR: wundergraph/cosmo-docs#261

@alepane21

Copy link
Copy Markdown
Contributor

Docs PR: wundergraph/cosmo-docs#261

Hi @vatsalpatel,
thank you for your contribution!
We recently moved documentation to this repo, inside the docs-website folder, so the external PR is not needed anymore, you can just add the docs changes inside this PR.

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

🧹 Nitpick comments (1)
router/pkg/config/config.schema.json (1)

2553-2579: Add schema-level dependency rules for mTLS fields.

Consider enforcing cert_file/key_file pairing and ca_file requirement directly in schema so invalid TLS combos fail at config validation time (not only at startup runtime).

🧩 Proposed schema refinement
                   "tls": {
                     "type": "object",
                     "description": "TLS configuration for the NATS provider.",
                     "additionalProperties": false,
                     "properties": {
                       "insecure_skip_verify": {
                         "type": "boolean",
                         "default": false,
                         "description": "Skip server certificate verification. Not recommended for production use."
                       },
                       "ca_file": {
                         "type": "string",
                         "description": "Path to a custom CA certificate file (PEM) used to verify the server certificate.",
                         "format": "file-path"
                       },
                       "cert_file": {
                         "type": "string",
                         "description": "Path to the client certificate file (PEM) for mTLS.",
                         "format": "file-path"
                       },
                       "key_file": {
                         "type": "string",
                         "description": "Path to the client private key file (PEM) for mTLS.",
                         "format": "file-path"
                       }
-                    }
+                    },
+                    "dependentRequired": {
+                      "cert_file": ["key_file"],
+                      "key_file": ["cert_file"]
+                    },
+                    "allOf": [
+                      {
+                        "if": {
+                          "anyOf": [
+                            { "required": ["cert_file"] },
+                            { "required": ["key_file"] }
+                          ]
+                        },
+                        "then": {
+                          "required": ["ca_file"]
+                        }
+                      }
+                    ]
                   },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@router/pkg/config/config.schema.json` around lines 2553 - 2579, The TLS
object currently allows cert_file/key_file/ca_file independently; add
schema-level rules under the "tls" object to enforce mTLS constraints: add an
allOf (or anyOf) clause that requires both "cert_file" and "key_file" to be
present together (e.g., an anyOf with {not having either} OR {having both}), and
add a rule that if either "cert_file" or "key_file" is present then "ca_file" is
required (use an if/then with "if":
{"anyOf":[{"required":["cert_file"]},{"required":["key_file"]}]} and "then":
{"required":["ca_file"]}). Reference the "tls" object and the property names
"cert_file", "key_file", and "ca_file" when applying these changes so invalid
mTLS combos fail validation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@router/pkg/config/config.schema.json`:
- Around line 2553-2579: The TLS object currently allows
cert_file/key_file/ca_file independently; add schema-level rules under the "tls"
object to enforce mTLS constraints: add an allOf (or anyOf) clause that requires
both "cert_file" and "key_file" to be present together (e.g., an anyOf with {not
having either} OR {having both}), and add a rule that if either "cert_file" or
"key_file" is present then "ca_file" is required (use an if/then with "if":
{"anyOf":[{"required":["cert_file"]},{"required":["key_file"]}]} and "then":
{"required":["ca_file"]}). Reference the "tls" object and the property names
"cert_file", "key_file", and "ca_file" when applying these changes so invalid
mTLS combos fail validation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: df69fa22-8ef3-4bec-91ea-391409508520

📥 Commits

Reviewing files that changed from the base of the PR and between 65efe37 and 288f382.

📒 Files selected for processing (6)
  • router/pkg/config/config.go
  • router/pkg/config/config.schema.json
  • router/pkg/config/config_events_nats_test.go
  • router/pkg/config/testdata/config_full.json
  • router/pkg/pubsub/nats/provider_builder.go
  • router/pkg/pubsub/nats/provider_builder_test.go

@vatsalpatel
vatsalpatel requested review from a team as code owners April 8, 2026 06:39
@vatsalpatel
vatsalpatel requested a review from JivusAyrus April 8, 2026 06:39
@vatsalpatel

Copy link
Copy Markdown
Contributor Author

Updated docs-website @alepane21
Should I close the cosmo-docs PR?

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs-website/router/configuration.mdx`:
- Around line 1753-1769: Update the TLS field descriptions so they explicitly
state runtime validation rules: in the table entries for tls.cert_file and
tls.key_file mention that cert_file and key_file must be provided together (both
required for mTLS) and that tls.ca_file is also required whenever either
cert_file or key_file is set; also update tls.ca_file description to note it is
required when using cert_file/key_file for mutual TLS. Ensure references to
tls.cert_file, tls.key_file and tls.ca_file are clear so readers know the valid
combinations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 22027364-1964-485f-8a2c-5def3c5d3284

📥 Commits

Reviewing files that changed from the base of the PR and between 288f382 and a2895ef.

📒 Files selected for processing (1)
  • docs-website/router/configuration.mdx

Comment thread docs-website/router/configuration.mdx Resolved
@alepane21

Copy link
Copy Markdown
Contributor

Updated docs-website @alepane21 Should I close the cosmo-docs PR?

Don't worry, I did it! Thanks again.

@dkorittki

Copy link
Copy Markdown
Contributor

Hey @vatsalpatel, thanks for your contribution! Just wanted to let you know I am looking into your pull request and will provide feedback very soon.

@dkorittki dkorittki 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 again for contribution, really appreciate it! The implementation looks good and works as expected. I left some comments on areas which need some touches.

In general what it lacks are some integration tests, which verify tls works against a real nats server instance. The right place to do this would be the router-tests module but I think it's asked too much for, since it would become rather complex. I will brainstorm a few ideas on how to solve this but meantime I want to provide some feedback to you already

Comment thread router/pkg/config/config.schema.json Resolved
Comment thread router/pkg/config/config.schema.json Resolved

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

🧹 Nitpick comments (1)
router/pkg/pubsub/nats/provider_builder.go (1)

121-123: Add explicit TLS minimum version for deterministic security posture.

The tls.Config at line 121 relies on Go's default MinVersion (TLS 1.2), which may change across Go runtime versions. For production NATS connections, explicitly set MinVersion: tls.VersionTLS13 to enforce consistent security guarantees.

Suggested change
 		tlsCfg := &tls.Config{
+			MinVersion:         tls.VersionTLS13,
 			InsecureSkipVerify: eventSource.TLS.InsecureSkipVerify,
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@router/pkg/pubsub/nats/provider_builder.go` around lines 121 - 123, The
tls.Config construction in provider_builder.go currently sets only
InsecureSkipVerify via tlsCfg and relies on Go's default MinVersion; update the
tlsCfg in the build path that creates tls.Config (the tlsCfg variable used for
NATS connections) to explicitly set MinVersion: tls.VersionTLS13 alongside
InsecureSkipVerify (using eventSource.TLS.InsecureSkipVerify) so the NATS client
enforces TLS 1.3 minimum.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@router/pkg/pubsub/nats/provider_builder.go`:
- Around line 121-123: The tls.Config construction in provider_builder.go
currently sets only InsecureSkipVerify via tlsCfg and relies on Go's default
MinVersion; update the tlsCfg in the build path that creates tls.Config (the
tlsCfg variable used for NATS connections) to explicitly set MinVersion:
tls.VersionTLS13 alongside InsecureSkipVerify (using
eventSource.TLS.InsecureSkipVerify) so the NATS client enforces TLS 1.3 minimum.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7fb3e057-98c3-44a8-8085-ecd6a43bfbdd

📥 Commits

Reviewing files that changed from the base of the PR and between 58b9ebc and 76260e5.

📒 Files selected for processing (5)
  • docs-website/router/configuration.mdx
  • router/pkg/config/config.schema.json
  • router/pkg/config/config_events_nats_test.go
  • router/pkg/pubsub/nats/provider_builder.go
  • router/pkg/pubsub/nats/provider_builder_test.go
✅ Files skipped from review due to trivial changes (2)
  • docs-website/router/configuration.mdx
  • router/pkg/pubsub/nats/provider_builder_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • router/pkg/config/config.schema.json
  • router/pkg/config/config_events_nats_test.go

@vatsalpatel

vatsalpatel commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey @dkorittki
Thank you for the review!
I have made all of the requested changes

  • Making CA cert optional for mTLS
  • More explicit assertations for nats options that are generated
  • Improved documentation listing explicit dependencies of TLS files

For the integration test, I did some research and there are 2 options we can go for

  1. We can use https://pkg.go.dev/github.com/nats-io/nats-server/v2/test which provides an easy to setup a test server
  opts := &server.Options{
      Host:      "127.0.0.1",
      Port:      -1,
      NoLog:     true,
  }
  s := natstest.RunServer(opts)
  t.Cleanup(s.Shutdown)
  s.ReadyForConnections(5 * time.Second)
  1. We can use testcontainers-go, but this will require docker to be running.

I think option 1 seems better, however we will have to add nats-server pkg to go.mod. If that is fine with you, I will update the integration tests.

Also FYI, looks like the router CI does setup a nats container and run integration tests against it.

    services:
      nats:
        image: ghcr.io/wundergraph/cosmo/nats:2.11.0-alpine

@vatsalpatel
vatsalpatel requested a review from dkorittki April 14, 2026 10:48
@dkorittki

dkorittki commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

We have the router-tests module, which contains all of our integration tests for the router. It configures the router to connect to a real nats instance but there is no easy way of enabling TLS for specific tests, to test TLS connectivity. The best option I see is going forward without such a test for now and I'll add one very soon in a seperate pull request. I verified that your changes work and not having a test for it temporarily is no big risk from my point of view. I'll review the latest changes from you and once approved I'll merge it as is

@codecov

codecov Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.46%. Comparing base (b712757) to head (a65f535).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
router/pkg/pubsub/nats/provider_builder.go 0.00% 27 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2749      +/-   ##
==========================================
- Coverage   65.99%   59.46%   -6.53%     
==========================================
  Files         254      238      -16     
  Lines       33221    32487     -734     
==========================================
- Hits        21924    19319    -2605     
- Misses       9908    11665    +1757     
- Partials     1389     1503     +114     
Files with missing lines Coverage Δ
router/pkg/config/config.go 54.80% <ø> (-26.93%) ⬇️
router/pkg/pubsub/nats/provider_builder.go 47.24% <0.00%> (-19.43%) ⬇️

... and 124 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread router/pkg/config/config.go Resolved
Comment thread router/pkg/config/config.go Resolved
@dkorittki

Copy link
Copy Markdown
Contributor

Good points from @SkArchon . @vatsalpatel can you address them as well?

@vatsalpatel

vatsalpatel commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you for the review @SkArchon
I have added the Enabled flag and made the other requested changes as well. I have also updated the test cases and the docs.
Please let me know if any other changes are required!

CC: @dkorittki

@dkorittki

Copy link
Copy Markdown
Contributor

Hey @vatsalpatel , thanks for the work you put in here! Just two more things. Can you remove the enabled flag? See #2749 (comment). Sorry for the inconvinience. Also can you rename the config parameter insecure_skip_verify to insecure_skip_ca_verification. This keeps it consistent to other tls sections we have in the router config.

@vatsalpatel

Copy link
Copy Markdown
Contributor Author

Hey @dkorittki and @SkArchon
I have removed the enabled flag and also renamed the insecure_skip_ca_verification field. Please review the changes again

@dkorittki

Copy link
Copy Markdown
Contributor

Looking good from my side but still need a rereview from @SkArchon

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

Approved, Dominik will add a schema validation

@dkorittki
dkorittki merged commit a73636b into wundergraph:main Apr 23, 2026
33 checks passed
@dkorittki

Copy link
Copy Markdown
Contributor

Merged. It will be part of the next router release. Thanks again for the contribution @vatsalpatel
I linked the pull request containing integration tests, which will be ready for review soon

@vatsalpatel

Copy link
Copy Markdown
Contributor Author

Thank you @dkorittki and @SkArchon for the review and the feedback!
Looking forward to the integration PR as well. Let me know if I can help in any way

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.

feat(router): add TLS support for NATS event source (skip verify, custom CA, mTLS)

4 participants