Skip to content

feat: add protovalidate interceptor to default chain#35

Merged
ankurs merged 3 commits intomainfrom
feat/protovalidate
Apr 6, 2026
Merged

feat: add protovalidate interceptor to default chain#35
ankurs merged 3 commits intomainfrom
feat/protovalidate

Conversation

@ankurs
Copy link
Copy Markdown
Member

@ankurs ankurs commented Apr 6, 2026

Summary

  • Add ProtoValidateInterceptor() and ProtoValidateStreamInterceptor() using go-grpc-middleware's protovalidate interceptor
  • Default on in both unary and stream chains (after TraceId, before Prometheus metrics)
  • Uses protovalidate.GlobalValidator by default (shared caching, zero config)
  • SetProtoValidateOptions() for custom constraints during init
  • Zero cost if no validation annotations in proto (just a type assertion)
  • Returns InvalidArgument gRPC status on validation failure

Chain order: ResponseTimeLogging → TraceId → ProtoValidate → Prometheus → ServerError → NewRelic → PanicRecovery

Test plan

  • go test -race ./... passes
  • make lint — 0 issues

Summary by CodeRabbit

Release Notes

  • New Features

    • Request validation is now automatically performed on Protocol Buffer messages for both unary and streaming RPC calls
    • Invalid requests return appropriate error responses
    • Validation behavior can be customized through configuration options
  • Documentation

    • Updated documentation with references to new validation interceptor APIs

Add ProtoValidateInterceptor and ProtoValidateStreamInterceptor using
go-grpc-middleware's protovalidate interceptor with buf.build/go/protovalidate.
Default on in the interceptor chain (after TraceId, before Prometheus metrics).
Zero cost if no validation annotations in proto.

Users can add custom validator options via SetProtoValidateOptions() during init.
Uses GlobalValidator by default for shared caching.
Copilot AI review requested due to automatic review settings April 6, 2026 02:46
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 6, 2026

Warning

Rate limit exceeded

@ankurs has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 10 minutes and 8 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 10 minutes and 8 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 790380f8-bf43-4dc6-8a27-3f6b4af55ecc

📥 Commits

Reviewing files that changed from the base of the PR and between ccd5951 and ba585bc.

📒 Files selected for processing (2)
  • README.md
  • interceptors.go
📝 Walkthrough

Walkthrough

This PR adds protovalidate-based request validation to the gRPC server interceptor chain. It introduces three new exported functions (ProtoValidateInterceptor(), ProtoValidateStreamInterceptor(), and SetProtoValidateOptions()) and integrates them into the default interceptor chains, with supporting dependency additions to go.mod.

Changes

Cohort / File(s) Summary
Interceptor Implementation
interceptors.go
Added ProtoValidateInterceptor() and ProtoValidateStreamInterceptor() constructors that create interceptors for unary and stream RPCs respectively. Introduced SetProtoValidateOptions() configuration function to customize validator behavior. Both interceptors are wired into DefaultInterceptors() and DefaultStreamInterceptors() chains.
Dependencies
go.mod
Added buf.build/go/protovalidate v1.1.3 as a direct dependency, plus transitive dependencies: buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go, cel.dev/expr, github.com/antlr4-go/antlr/v4, github.com/google/cel-go, and golang.org/x/exp.
Documentation
README.md
Added documentation entries for the three new exported functions with descriptions of protovalidate-based validation behavior and InvalidArgument error handling. Updated existing README anchor links to reflect line number shifts.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • perf: cache interceptor chain in DoHTTPtoGRPC #22: This PR updates the default interceptor chains returned by DefaultInterceptors() and DefaultStreamInterceptors(), which would directly affect PR #22's caching mechanism for the interceptor chain in DoHTTPtoGRPC.

Poem

🐰 Validation hops through every frame,
Protocol buffers bend and tame,
Invalid arguments bounce with care,
While streams and unary messages fare,
Through protovalidate's vigilant air!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: adding protovalidate interceptor support to the default interceptor chain, which is the core objective of this PR.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/protovalidate

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.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds request validation to the default gRPC server interceptor chains by integrating Buf’s protovalidate via go-grpc-middleware, with optional init-time customization.

Changes:

  • Introduces ProtoValidateInterceptor() and ProtoValidateStreamInterceptor() backed by protovalidate.GlobalValidator by default.
  • Adds SetProtoValidateOptions(...) and wires protovalidate into the default unary and stream server interceptor chains (before Prometheus metrics).
  • Updates module dependencies/docs to include protovalidate.

Reviewed changes

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

File Description
README.md Documents new protovalidate interceptors and init-time configuration API.
interceptors.go Implements protovalidate interceptors/options and inserts them into default chains.
go.mod Adds protovalidate dependency (and indirect transitive deps).
go.sum Records checksums for newly added dependencies.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread interceptors.go Outdated
Comment thread interceptors.go Outdated
Comment thread interceptors.go
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

Inline comments:
In `@interceptors.go`:
- Around line 260-266: The stream interceptor is discarding the error from
protovalidate.New() in ProtoValidateStreamInterceptor; extract validator
creation into a helper (e.g., createProtoValidator or initProtoValidator) that
calls protovalidate.New(protoValidateOpts...) and panics if it returns an error,
then have ProtoValidateStreamInterceptor call that helper and pass the returned
validator to protovalidate_middleware.StreamServerInterceptor (falling back to
protovalidate.GlobalValidator only if no opts exist).
- Around line 250-256: The ProtoValidateInterceptor currently discards the error
from protovalidate.New(protoValidateOpts...), which can produce a nil validator
and cause runtime panics; update ProtoValidateInterceptor to check the returned
error from protovalidate.New (when protoValidateOpts is non-empty) and panic (or
log.Fatal) with a clear message if err != nil so initialization fails fast;
otherwise continue to return protovalidate_middleware.UnaryServerInterceptor(v)
on success, and keep the existing fallback to
protovalidate_middleware.UnaryServerInterceptor(protovalidate.GlobalValidator)
when protoValidateOpts is empty.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: e7b76428-d8f7-4f30-8f88-466a16dfb2f6

📥 Commits

Reviewing files that changed from the base of the PR and between 0a5b348 and ccd5951.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (3)
  • README.md
  • go.mod
  • interceptors.go

Comment thread interceptors.go
Comment thread interceptors.go
- Cache validator via sync.Once so it's created once, not per call
- Log error and fall back to GlobalValidator if custom options fail
- Extract getProtoValidator() helper used by both unary and stream
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

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 3 out of 4 changed files in this pull request and generated 1 comment.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread interceptors.go
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

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 3 out of 4 changed files in this pull request and generated 2 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread interceptors.go
Comment thread interceptors.go
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