-
Notifications
You must be signed in to change notification settings - Fork 212
refactor: PR 1.5 implement pure options pattern for middleware with core integration #360
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
developerkunal
wants to merge
6
commits into
v3-phase1-pr4-jwx-migration
Choose a base branch
from
v3-phase1-pr5-middleware-options
base: v3-phase1-pr4-jwx-migration
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
refactor: PR 1.5 implement pure options pattern for middleware with core integration #360
developerkunal
wants to merge
6
commits into
v3-phase1-pr4-jwx-migration
from
v3-phase1-pr5-middleware-options
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
…egration
Changes:
- Refactor middleware constructor from New(validateToken, opts...) to New(opts...)
- Add WithValidateToken() as required option with fail-fast validation
- Integrate middleware with core package using validatorAdapter bridge
- Implement unexported contextKey int pattern for collision-free context storage
- Add type-safe generic claims access: GetClaims[T](), MustGetClaims[T](), HasClaims()
Logging:
- Add WithLogger() option for comprehensive JWT validation logging
- Implement debug, warn, and error logging throughout CheckJWT flow
- Propagate logger from middleware through core to validator
- Log token extraction, validation, errors, and exclusion handling
Error Handling:
- Implement RFC 6750 OAuth 2.0 Bearer Token error responses
- Add structured ErrorResponse with error/error_description/error_code fields
- Generate WWW-Authenticate headers for all error responses
- Design extensible architecture for future DPoP (RFC 9449) support
- Add comprehensive error handler tests (13 scenarios)
Token Extractors:
- Add input validation to CookieTokenExtractor and ParameterTokenExtractor
- Fix cookie error handling to propagate non-ErrNoCookie errors
- Add tests for case-insensitive Bearer scheme and edge cases
- Validate empty parameter/cookie names at construction time
Tests:
- Add option_test.go with comprehensive coverage of all options
- Add logger integration tests covering all CheckJWT paths
- Add invalidError tests for Error(), Is(), and Unwrap() methods
- Add extractor edge case tests (uppercase, mixed case, multiple spaces)
- Achieve 99.4% total coverage (main: 98.2%, core: 100%, validator: 100%)
Examples:
- Update all examples (http, jwks, gin, echo, iris) to use new API
- Replace old constructor calls with pure options pattern
- Update claims access to use generic GetClaims[T]() API
- Add commented logger examples in http-example
Breaking Changes:
- Constructor signature: New(opts...) instead of New(validateToken, opts...)
- Claims access: GetClaims[T](ctx) instead of ctx.Value(ContextKey{})
- Context key changed to unexported type for collision prevention
Test Coverage:
- Main middleware: 98.2%
- Core: 100.0%
- Validator: 100.0%
- JWKS: 100.0%
- OIDC: 100.0%
- Total: 99.4%
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## v3-phase1-pr4-jwx-migration #360 +/- ##
===============================================================
- Coverage 99.46% 98.88% -0.59%
===============================================================
Files 13 13
Lines 562 718 +156
===============================================================
+ Hits 559 710 +151
- Misses 3 4 +1
- Partials 0 4 +4 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
2 tasks
Remove duplicate context key management from HTTP middleware and use core's SetClaims/GetClaims/HasClaims functions consistently. This establishes the standard pattern for all adapters. Changes: - Remove contextKey and claimsContextKey from middleware.go - Update CheckJWT to use core.SetClaims() for storing claims - Update GetClaims/MustGetClaims/HasClaims to delegate to core - Update test assertion to match core's error message Benefits: - Single source of truth for context key management in core - All adapters (HTTP, gRPC, Gin, Echo) will use same context key - Claims stored by any adapter can be retrieved by any other adapter - Zero collision risk with unexported contextKey type in core - Maintains clean API - HTTP users don't need to import core This ensures cross-adapter compatibility while keeping the HTTP middleware API user-friendly with convenience wrappers.
- Change WithValidateToken to WithValidator to accept *validator.Validator - Update ErrValidateTokenNil to ErrValidatorNil - Refactor validatorAdapter to use TokenValidator interface - Update all examples (http, http-jwks, gin, echo, iris) to use WithValidator - Add setupRouter/setupApp functions to all examples for testability - Create comprehensive integration tests for all examples - Update test fixtures to use non-expiring test token (expires 2099) - Add testify dependency to example projects for testing - Fix iris example to use iris native httptest package This change enables future extensibility for methods like ValidateDPoP by allowing explicit passing of the validator instance.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📝 Checklist
🔧 Changes
This PR refactors the middleware to use a pure options pattern and integrates it with the new core package.
Types and Functions Changed:
Constructor:
New(validateToken ValidateToken, opts ...Option)→New(opts ...Option) (*JWTMiddleware, error)type Option func(*JWTMiddleware) errorNew Functions:
WithValidateToken(ValidateToken) Option- Required option for token validationWithLogger(Logger) Option- Optional logger for debugging JWT flowGetClaims[T any](context.Context) (T, error)- Generic type-safe claims retrievalMustGetClaims[T any](context.Context) T- Panicking variant of GetClaimsHasClaims(context.Context) bool- Check if claims exist in contextTypes Added:
Logger interface- Logging interface compatible with log/slogErrorResponse struct- Structured JSON error responsevalidatorAdapter struct- Bridge between ValidateToken and core.TokenValidatorError Handling:
DefaultErrorHandler- Rewritten for RFC 6750 OAuth 2.0 Bearer Token complianceToken Extractors:
CookieTokenExtractor(string) TokenExtractor- Now validates empty cookie namesParameterTokenExtractor(string) TokenExtractor- Now validates empty parameter namesContext Key:
type ContextKey struct{}to unexportedtype contextKey intUsage Summary:
Before:
After:
Test Coverage:
📚 References
🔬 Testing
Automated Tests:
option_test.gowith comprehensive option validation testsTest_invalidErrorfor error wrapper methodsManual Testing:
All examples have been updated and build successfully:
Testing Steps:
make test- All tests pass with 99.4% coveragemake lint- Zero linting issues