Skip to content

Conversation

@developerkunal
Copy link
Contributor

@developerkunal developerkunal commented Nov 21, 2025

📝 Checklist

  • All new/changed/fixed functionality is covered by tests (or N/A)
  • I have added documentation for all new/changed functionality (or N/A)

🔧 Changes

Refactors validator.New() from positional parameters to a pure options pattern. Introduces generic type-safe custom claims handling.

Breaking Changes:

// Before
validator.New(keyFunc, algorithm, issuer, audience, opts...)

// After
validator.New(
    validator.WithKeyFunc(keyFunc),
    validator.WithAlgorithm(validator.RS256),
    validator.WithIssuer("https://issuer.example.com/"),
    validator.WithAudience("my-api"),
)

New Options:

Required:

  • WithKeyFunc(func) - Key function for token verification
  • WithAlgorithm(SignatureAlgorithm) - Signature algorithm
  • WithIssuer(string) - Expected issuer claim
  • WithAudience(string) / WithAudiences([]string) - Expected audience(s)

Optional:

  • WithCustomClaims[T CustomClaims](func() T) - Type-safe custom claims (now generic)
  • WithAllowedClockSkew(duration) - Clock skew tolerance

Type-Safe Custom Claims:

// Before
customClaims := func() validator.CustomClaims {
    return &CustomClaimsExample{}
}
validator.WithCustomClaims(customClaims)

// After
validator.WithCustomClaims(func() *CustomClaimsExample {
    return &CustomClaimsExample{}  // No interface cast needed
})

Files Modified:

  • validator/option.go - Required options + generic WithCustomClaims
  • validator/validator.go - Refactored constructor
  • validator/validator_test.go - Updated tests
  • validator/security_test.go - Updated CVE test
  • middleware_test.go - Updated tests
  • All examples updated

📚 References

  • Depends on PR 1.2 (Core Logic)
  • Required for PR 1.4 (jwx Migration)

🔬 Testing

make test
# validator:     100.0% coverage ✅
# main package:   97.4% coverage ✅
# oidc:          100.0% coverage ✅
# jwks:           95.8% coverage ✅

All examples verified to build successfully.

   This implements the Core-Adapter Architecture for v3, separating
   framework-agnostic validation logic from transport-specific adapters.

   Key Features:
   - Core struct with CheckToken method for pure validation logic
   - Options pattern with error-returning option functions
   - Type-safe context helpers using generics (GetClaims[T])
   - Unexported contextKey int to prevent collisions (Go best practice)
   - Structured error types with error codes
   - Logger interface for observability
   - 100% test coverage

   Changes:
   - Add core/core.go: Framework-agnostic validation engine
   - Add core/option.go: Options pattern with validation
   - Add core/errors.go: Structured errors and error codes
   - Add core/context.go: Type-safe context helpers
   - Add core/core_test.go: Comprehensive tests

   This enables future support for multiple frameworks (HTTP, gRPC, Gin,
   Echo, etc.) by wrapping the Core with transport-specific adapters.

   Part of PR 1.2 in v3 Phase 1 implementation.
Refactors validator.New() from positional parameters to pure options pattern, improving API consistency and extensibility.

Breaking Changes:

- validator.New() now takes only options (no positional parameters)

- All parameters must now use option functions

Before:

  validator.New(keyFunc, algorithm, issuer, audience, opts...)

After:

  validator.New(

    validator.WithKeyFunc(keyFunc),

    validator.WithAlgorithm(validator.RS256),

    validator.WithIssuer("https://issuer.example.com/"),

    validator.WithAudience("my-api"),

  )

New Options:

- WithKeyFunc: Required key function

- WithAlgorithm: Required signature algorithm

- WithIssuer: Required issuer URL (with validation)

- WithAudience/WithAudiences: Required audience(s)

Coverage:

- validator package: 100.0%

- All tests passing

- All examples updated
@developerkunal developerkunal requested a review from a team as a code owner November 21, 2025 09:28
@codecov-commenter
Copy link

codecov-commenter commented Nov 21, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (v3-dev@ef09df6). Learn more about missing BASE report.

Additional details and impacted files
@@            Coverage Diff            @@
##             v3-dev     #357   +/-   ##
=========================================
  Coverage          ?   97.95%           
=========================================
  Files             ?       13           
  Lines             ?      441           
  Branches          ?        0           
=========================================
  Hits              ?      432           
  Misses            ?        6           
  Partials          ?        3           

☔ View full report in Codecov by Sentry.
📢 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.

Introduces generics to WithCustomClaims for improved type safety, cleaner API ergonomics and better developer experience.

Summary of Improvements

What Changed

Before (non-generic):

  validator.WithCustomClaims(func() validator.CustomClaims {

      return &MyClaims{}

  })

After (with generics):

  validator.WithCustomClaims(func() *MyClaims {

      return &MyClaims{}

  })

Benefits

1. Type Safety. Compiler ensures T implements CustomClaims at compile time.

2. Cleaner API. Users no longer need to return interface types explicitly.

3. Better IDE Support. Autocomplete works with concrete types.

4. Flexible. Allows nil returns for conditional custom claims with identical runtime behavior.

5. Full Coverage. All tests pass.

Implementation Details

- Introduces WithCustomClaims[T CustomClaims](f func() T)

- Wraps user function internally to return the interface

- No breaking changes. All existing usage continues to work

- Type parameter is inferred from function return type

- Nil functions require explicit type: WithCustomClaims[*MyClaims](nil)

Test Results

- validator package: 100.0 percent coverage

- All tests passing
Updates all example projects to use the new generic WithCustomClaims API and to reference the v3 module path. All example builds succeed with the updated validator version.

Changes included:

1. Updated every example to use the new generic WithCustomClaims syntax across gin, echo, http and iris.

2. Updated each example go.mod file to reference v3 rather than v2 and added the appropriate replace directives.

3. Verified that all examples build correctly with the revised API.
@developerkunal developerkunal changed the base branch from v3-phase1-pr1-project-setup to v3-phase1-pr2-core-package November 21, 2025 10:00
@developerkunal developerkunal changed the title PR 1.3: Refactor validator to use pure options pattern refactor: PR 1.3: Refactor validator to use pure options pattern Nov 21, 2025
@developerkunal developerkunal changed the title refactor: PR 1.3: Refactor validator to use pure options pattern refactor: PR 1.3 Refactor validator to use pure options pattern Nov 21, 2025
Base automatically changed from v3-phase1-pr2-core-package to v3-dev December 8, 2025 05:59
@developerkunal developerkunal merged commit 76eed4e into v3-dev Dec 8, 2025
6 checks passed
@developerkunal developerkunal deleted the v3-phase1-pr3-validator-options branch December 8, 2025 06:14
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.

4 participants