Skip to content

[TT-10273] CORS check should be performed after API Version check #7179

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

Conversation

MaciekMis
Copy link
Contributor

@MaciekMis MaciekMis commented Jul 1, 2025

User description

TT-10273
Summary [OAS] CORS check should be performed after API Version check
Type Bug Bug
Status In Dev
Points N/A
Labels codilime_refined

Description

The current implementation applies CORS middleware at the router level, which executes before the API Version Check middleware in the chain. This means that for versioned Tyk OAS APIs, the CORS configuration from the base API is always used, regardless of any version-specific CORS configurations.

Related Issue

Motivation and Context

How This Has Been Tested

Screenshots (if appropriate)

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring or add test (improvements in base code or adds test coverage to functionality)

Checklist

  • I ensured that the documentation is up to date
  • I explained why this PR updates go.mod in detail with reasoning why it's required
  • I would like a code coverage CI quality gate exception and have explained why

PR Type

Bug fix, Enhancement, Tests


Description

  • Refactored CORS handling into a dedicated middleware for correct execution order

  • Ensured CORS checks occur after API version checks for OAS APIs

  • Updated OAuth endpoint handlers to apply CORS only when enabled

  • Added comprehensive unit and integration tests for the new CORS middleware


Changes diagram

flowchart LR
  OldCORS["CORS at router level"] -- "removed" --> X1[""]
  VersionCheck["API Version Check Middleware"] -- "now before" --> NewCORS["CORSMiddleware"]
  NewCORS -- "added to middleware chain" --> APIHandler["API Handler"]
  OAuthEndpoints["OAuth Endpoints"] -- "wrapped with CORS if enabled" --> OAuthCORS["CORS Wrapper"]
  TestsOld["Old CORS tests"] -- "removed" --> X2[""]
  TestsNew["New CORSMiddleware tests"] -- "added" --> CORSMiddleware
Loading

Changes walkthrough 📝

Relevant files
Enhancement
api_loader.go
Move CORS handling to middleware chain after version check

gateway/api_loader.go

  • Removed router-level CORS middleware application
  • Added CORSMiddleware to the middleware chain after version check
  • +1/-16   
    mw_cors.go
    Add CORSMiddleware implementation for CORS handling           

    gateway/mw_cors.go

  • Introduced CORSMiddleware struct and logic
  • Handles CORS requests as part of middleware chain
  • Returns early for preflight OPTIONS requests
  • +43/-0   
    server.go
    Apply CORS wrapper to OAuth endpoints when enabled             

    gateway/server.go

  • Updated OAuth endpoint handlers to wrap with CORS only if enabled
  • Added createCORSWrapper utility for conditional CORS wrapping
  • +34/-4   
    Tests
    api_loader_test.go
    Remove outdated CORS tests                                                             

    gateway/api_loader_test.go

    • Removed legacy CORS test function
    +0/-73   
    mw_cors_test.go
    Add comprehensive CORSMiddleware tests                                     

    gateway/mw_cors_test.go

  • Added unit tests for CORSMiddleware logic
  • Added integration tests for CORS behavior on APIs and OAuth endpoints
  • Utility functions for CORS config and middleware creation
  • +157/-0 

    Need help?
  • Type /help how to ... in the comments thread for any questions about PR-Agent usage.
  • Check out the documentation for more information.
  • @buger
    Copy link
    Member

    buger commented Jul 1, 2025

    I'm a bot and I 👍 this PR title. 🤖

    Copy link
    Contributor

    github-actions bot commented Jul 1, 2025

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Middleware Ordering

    The new CORS middleware is now inserted after the API Version Check middleware. The reviewer should validate that this ordering does not introduce unintended side effects, especially for APIs with version-specific CORS configurations or custom middleware chains.

    type CORSMiddleware struct {
    	*BaseMiddleware
    	corsHandler *cors.Cors
    }
    
    func (c *CORSMiddleware) Name() string {
    	return "CORSMiddleware"
    }
    
    func (c *CORSMiddleware) EnabledForSpec() bool {
    	return c.Spec.CORS.Enable
    }
    
    func (c *CORSMiddleware) Init() {
    	c.corsHandler = cors.New(cors.Options{
    		AllowedOrigins:     c.Spec.CORS.AllowedOrigins,
    		AllowedMethods:     c.Spec.CORS.AllowedMethods,
    		AllowedHeaders:     c.Spec.CORS.AllowedHeaders,
    		ExposedHeaders:     c.Spec.CORS.ExposedHeaders,
    		AllowCredentials:   c.Spec.CORS.AllowCredentials,
    		MaxAge:             c.Spec.CORS.MaxAge,
    		OptionsPassthrough: c.Spec.CORS.OptionsPassthrough,
    		Debug:              c.Spec.CORS.Debug,
    	})
    }
    
    func (c *CORSMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
    	c.corsHandler.HandlerFunc(w, r)
    
    	if r.Method == http.MethodOptions && !c.Spec.CORS.OptionsPassthrough {
    		return nil, middleware.StatusRespond
    	}
    
    	return nil, http.StatusOK
    }
    OAuth Endpoint CORS Handling

    The OAuth endpoints are now wrapped with a CORS handler using the new createCORSWrapper function. The reviewer should ensure that this approach correctly applies CORS headers and does not interfere with OAuth flows or introduce regressions in authentication/authorization behavior.

    	gw,
    }
    
    osinServer := gw.TykOsinNewServer(serverConfig, osinStorage)
    
    oauthManager := OAuthManager{spec, osinServer, gw}
    oauthHandlers := OAuthHandlers{oauthManager}
    
    wrapWithCORS := createCORSWrapper(spec)
    
    muxer.Handle(apiAuthorizePath, gw.checkIsAPIOwner(allowMethods(oauthHandlers.HandleGenerateAuthCodeData, "POST")))
    muxer.HandleFunc(clientAuthPath, wrapWithCORS(allowMethods(oauthHandlers.HandleAuthorizePassthrough, "GET", "POST")))
    muxer.HandleFunc(clientAccessPath, wrapWithCORS(addSecureAndCacheHeaders(allowMethods(oauthHandlers.HandleAccessRequest, "GET", "POST"))))
    muxer.HandleFunc(revokeToken, wrapWithCORS(oauthHandlers.HandleRevokeToken))
    muxer.HandleFunc(revokeAllTokens, wrapWithCORS(oauthHandlers.HandleRevokeAllTokens))
    return &oauthManager
    Removal of Router-Level CORS Middleware

    The previous router-level CORS middleware application has been removed in favor of middleware-based handling. The reviewer should check that all routes, including edge cases, still receive appropriate CORS handling and that there are no regressions for APIs relying on the old behavior.

    func (gw *Gateway) generateSubRoutes(spec *APISpec, router *mux.Router) {
    	if spec.GraphQL.GraphQLPlayground.Enabled {
    		gw.loadGraphQLPlayground(spec, router)
    	}
    
    	if spec.EnableBatchRequestSupport {
    		gw.addBatchEndpoint(spec, router)
    	}
    
    	if spec.UseOauth2 {
    		oauthManager := gw.addOAuthHandlers(spec, router)
    		spec.OAuthManager = oauthManager
    	}
    }

    Copy link
    Contributor

    github-actions bot commented Jul 1, 2025

    API Changes

    --- prev.txt	2025-07-17 12:39:26.140839266 +0000
    +++ current.txt	2025-07-17 12:39:16.489822435 +0000
    @@ -9096,6 +9096,19 @@
     }
         BundleSaver is an interface used by bundle saver structures.
     
    +type CORSMiddleware struct {
    +	*BaseMiddleware
    +	// Has unexported fields.
    +}
    +
    +func (c *CORSMiddleware) EnabledForSpec() bool
    +
    +func (c *CORSMiddleware) Init()
    +
    +func (c *CORSMiddleware) Name() string
    +
    +func (c *CORSMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
    +
     type CertificateCheckMW struct {
     	*BaseMiddleware
     }

    Copy link
    Contributor

    github-actions bot commented Jul 1, 2025

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Prevent CORS middleware from writing body on non-OPTIONS

    The call to c.corsHandler.HandlerFunc(w, r) may write headers or a response body
    even for non-OPTIONS requests, which could interfere with subsequent middleware or
    handlers. Ensure that for non-OPTIONS requests, the middleware does not prematurely
    write a response or headers unless required by CORS.

    gateway/mw_cors.go [35-43]

     func (c *CORSMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
    -	c.corsHandler.HandlerFunc(w, r)
    -
     	if r.Method == http.MethodOptions && !c.Spec.CORS.OptionsPassthrough {
    +		c.corsHandler.HandlerFunc(w, r)
     		return nil, middleware.StatusRespond
     	}
     
    +	// For non-OPTIONS, only set CORS headers, do not write body
    +	c.corsHandler.ServeHTTP(&middleware.HeaderOnlyResponseWriter{ResponseWriter: w}, r)
     	return nil, http.StatusOK
     }
    Suggestion importance[1-10]: 8

    __

    Why: This suggestion addresses a subtle but important issue: the original code may cause the CORS middleware to write headers or a response body for non-OPTIONS requests, potentially interfering with downstream handlers or middleware. The improved code ensures headers are set without writing a body, which is crucial for correct middleware chaining and HTTP response behavior.

    Medium

    Copy link
    Contributor

    @shults shults left a comment

    Choose a reason for hiding this comment

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

    lgtm

    @kofoworola
    Copy link
    Contributor

    /probe review it pls. Check for any change will break existing behaviour outside the ticket description

    Copy link
    Contributor

    @kofoworola kofoworola left a comment

    Choose a reason for hiding this comment

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

    Left some comments

    Copy link
    Contributor

    CORS Middleware Refactoring Analysis

    This PR addresses an issue with CORS (Cross-Origin Resource Sharing) handling in the Tyk API Gateway, specifically for versioned OAS APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API Version Check middleware. This meant that for versioned APIs, the base API's CORS configuration was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Removed Router-Level CORS Middleware:

      • The previous implementation applied CORS at the router level using router.Use(c.Handler) in the generateSubRoutes function, which executed before any API-specific middleware.
      • This router-level CORS handling has been completely removed from api_loader.go.
    2. Added Dedicated CORS Middleware:

      • Created a new CORSMiddleware struct in mw_cors.go that implements the middleware interface.
      • The middleware handles CORS preflight requests and applies CORS headers to regular requests.
      • For preflight OPTIONS requests, it returns early with middleware.StatusRespond to prevent further processing.
    3. Changed Middleware Ordering:

      • The new CORS middleware is now added to the middleware chain after the Version Check middleware:
        if enableVersionCheck {
            chainArray = append(chainArray, gw.createMiddleware(&VersionCheck{BaseMiddleware: &gw.BaseMiddleware}))
        }
        
        if spec.CORS.Enable {
            chainArray = append(chainArray, gw.createMiddleware(&CORSMiddleware{BaseMiddleware: &gw.BaseMiddleware}))
        }
      • This ensures that version-specific CORS configurations are respected.
    4. Updated OAuth Endpoint Handling:

      • Created a createCORSWrapper utility function that conditionally applies CORS handling to OAuth endpoints.
      • OAuth endpoints are now wrapped with CORS only when CORS is enabled for the API.
      • This ensures consistent CORS behavior across all API endpoints, including OAuth.
    5. Added Comprehensive Tests:

      • Added unit tests for the new CORS middleware, covering preflight requests, regular requests, and options passthrough.
      • Added integration tests to verify CORS behavior on API endpoints and OAuth endpoints.
      • Removed outdated CORS tests from api_loader_test.go.

    Benefits

    1. Correct Version-Specific CORS Handling: The primary issue is fixed - version-specific CORS configurations will now be respected because the CORS middleware executes after the version check.

    2. Consistent CORS Behavior: All endpoints, including OAuth endpoints, now have consistent CORS handling based on the API's configuration.

    3. Better Separation of Concerns: CORS handling is now encapsulated in a dedicated middleware, making the code more maintainable and easier to understand.

    4. Improved Testing: The new tests provide better coverage and validation of CORS behavior.

    Potential Considerations

    1. Header Writing in Non-OPTIONS Requests: As noted in a PR comment, the CORS middleware calls c.corsHandler.HandlerFunc(w, r) for all requests, which might write headers or a response body even for non-OPTIONS requests. This could potentially interfere with subsequent middleware or handlers. A suggested improvement was to use a header-only response writer for non-OPTIONS requests.

    2. Missing Unhappy Path Tests: A reviewer suggested adding tests for when the CORS host does not match the accepted host, which would improve test coverage for error cases.

    3. Removal of HeadersMatch Test: A reviewer questioned why a HeadersMatch test was removed from reverse_proxy_test.go. This should be verified to ensure no regression in functionality.

    Impact on Existing Behavior

    The PR changes how CORS is applied in the middleware chain, which could potentially affect existing APIs that rely on the current behavior. However, the change is designed to fix a bug where version-specific CORS configurations were not being respected, so the impact should be positive for most users.

    For non-versioned APIs, the behavior should remain the same, as the CORS middleware will still be applied, just at a different point in the chain. For versioned APIs, this change ensures that the correct version-specific CORS configuration is used.

    The OAuth endpoint handling has also been updated to conditionally apply CORS, which should provide more consistent behavior across all API endpoints.

    Overall, this PR represents a well-structured refactoring that addresses a specific issue with CORS handling in versioned APIs, with comprehensive tests to ensure the new implementation works correctly.


    Tip: Mention me again using /performance <request>.
    Powered by Probe AI

    Copy link
    Contributor

    CORS Middleware Execution Order Fix

    This PR addresses an important issue with CORS handling in Tyk Gateway, particularly for versioned APIs. The problem was that CORS middleware was being applied at the router level, which meant it executed before the API Version Check middleware in the chain. This caused versioned Tyk OAS APIs to always use the base API's CORS configuration, regardless of any version-specific CORS configurations.

    Key Changes

    1. Middleware Execution Order:

      • Removed the router-level CORS middleware application that was prepending the CORS handler to the beginning of the middleware chain
      • Added a dedicated CORSMiddleware struct that's inserted into the middleware chain immediately after the VersionCheck middleware
      • This ensures that version-specific CORS configurations are correctly applied after the API version is determined
    2. New CORSMiddleware Implementation:

      • Created a proper middleware implementation in mw_cors.go that follows the middleware interface pattern
      • The middleware initializes a CORS handler with the API spec's CORS configuration
      • For OPTIONS requests (preflight), it returns early with StatusRespond if OptionsPassthrough is false
      • For regular requests, it applies CORS headers and continues the middleware chain
    3. OAuth Endpoint Handling:

      • Updated OAuth endpoint handlers to conditionally apply CORS only when it's enabled for the API
      • Added a createCORSWrapper utility function that returns a no-op wrapper when CORS is disabled
    4. Test Coverage:

      • Removed outdated CORS tests from api_loader_test.go
      • Added comprehensive unit and integration tests for the new CORS middleware in mw_cors_test.go
      • Tests cover both preflight and regular requests, as well as OAuth endpoints with CORS

    This implementation ensures that CORS checks are performed after API version checks, allowing version-specific CORS configurations to be correctly applied. The change maintains backward compatibility while fixing the issue for versioned APIs.

    Potential Impact

    The PR should not break existing behavior for non-versioned APIs, as it simply moves the CORS handling from the router level to the middleware chain. For versioned APIs, it will now correctly apply version-specific CORS configurations, which is the intended behavior.

    The changes are well-tested with both unit tests and integration tests, covering various scenarios including preflight requests, regular requests, and OAuth endpoints with CORS.


    Tip: Mention me again using /connectivity <request>.
    Powered by Probe AI

    Copy link
    Contributor

    Analysis of PR #7179: CORS Check Should Be Performed After API Version Check

    This PR addresses an important issue with CORS handling in the Tyk API Gateway, specifically focusing on the order of middleware execution for versioned APIs. The problem was that CORS middleware was being applied at the router level, which executes before the API Version Check middleware in the chain. This meant that for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. New CORSMiddleware Implementation:

      • Created a dedicated CORSMiddleware struct that implements the Tyk middleware interface
      • The middleware handles CORS preflight requests and applies CORS headers to regular requests
      • For OPTIONS preflight requests, it returns early with appropriate CORS headers
      • For regular requests, it adds CORS headers and allows the request to continue through the middleware chain
    2. Middleware Chain Reordering:

      • Removed the router-level CORS middleware application from loadAPIEndpoints function
      • Added the new CORSMiddleware to the middleware chain after the VersionCheck middleware in buildMiddlewareChain
      • This ensures that version-specific CORS configurations are correctly applied
    3. OAuth Endpoint CORS Handling:

      • Updated the createCORSWrapper utility function that conditionally applies CORS handling to OAuth endpoints
      • Updated OAuth endpoint handlers to use this wrapper only when CORS is enabled for the API
      • This ensures consistent CORS behavior across all API endpoints
    4. Comprehensive Testing:

      • Added unit tests for the new CORSMiddleware functionality
      • Added integration tests that verify correct CORS behavior for versioned APIs
      • Tests confirm that version-specific CORS settings are properly applied

    Impact and Benefits

    1. Correct Version-Specific CORS Handling:

      • APIs with multiple versions can now have different CORS configurations per version
      • The correct CORS settings are applied based on the requested API version
      • This is particularly important for OAS APIs where different versions might need different CORS settings
    2. Consistent Middleware Architecture:

      • CORS handling now follows the same middleware pattern as other features
      • This makes the codebase more maintainable and consistent
      • The middleware chain is now properly ordered to ensure correct processing sequence
    3. Improved OAuth Endpoint Security:

      • OAuth endpoints now correctly respect the API's CORS configuration
      • This prevents potential security issues with cross-origin requests to OAuth endpoints

    Technical Implementation Details

    The implementation moves CORS handling from being a router-level middleware to a standard middleware in the chain:

    1. The new CORSMiddleware is placed after the VersionCheck middleware, ensuring that the correct API version is determined before CORS rules are applied.

    2. The middleware uses the CORS configuration from the API spec that's already been processed by the version check, ensuring version-specific settings are used.

    3. For OAuth endpoints, the createCORSWrapper function now conditionally applies CORS handling only when it's enabled for the API.

    4. The implementation maintains backward compatibility while fixing the issue, ensuring existing APIs continue to work as expected.

    This PR successfully resolves the issue by ensuring that CORS checks are performed after API version checks, allowing for proper version-specific CORS configurations to be applied.


    Tip: Mention me again using /dependency <request>.
    Powered by Probe AI

    Copy link
    Contributor

    CORS Middleware Refactoring Analysis

    This PR addresses an issue with CORS handling in Tyk Gateway, particularly for versioned OAS APIs. The problem was that CORS checks were being performed at the router level, which executed before the API Version Check middleware. This meant that for versioned APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Removed Router-Level CORS Handling:

      • Eliminated the CORS middleware application from the router in api_loader.go
      • This prevents CORS from being applied too early in the request lifecycle
    2. Created Dedicated CORS Middleware:

      • Implemented a new CORSMiddleware struct in mw_cors.go that properly integrates into the middleware chain
      • The middleware handles CORS preflight requests and applies CORS headers to regular requests
      • For OPTIONS requests, it returns early with middleware.StatusRespond to prevent further processing
      • For regular requests, it applies headers but allows the request to continue through the chain
    3. Positioned CORS After Version Check:

      • Placed the CORS middleware immediately after the VersionCheck middleware in the middleware chain
      • This ensures that version-specific CORS configurations are correctly applied
    4. Updated OAuth Endpoint Handling:

      • Added a createCORSWrapper function to conditionally apply CORS to OAuth endpoints
      • This ensures consistent CORS behavior across all API endpoints
    5. Added Comprehensive Tests:

      • Created unit tests for the CORS middleware functionality
      • Added integration tests to verify correct behavior in real-world scenarios

    Benefits

    This refactoring ensures that version-specific CORS configurations are properly respected in versioned Tyk OAS APIs. By moving CORS handling from the router level to the middleware chain, the system now correctly applies the CORS configuration associated with the specific API version being accessed, rather than always using the base API's configuration.

    The implementation is clean and follows the established middleware pattern in Tyk, making it maintainable and consistent with the rest of the codebase.


    Tip: Mention me again using /security <request>.
    Powered by Probe AI

    Copy link
    Contributor

    CORS Middleware Execution Order Fix Analysis

    This PR addresses an important issue with CORS handling in the Tyk Gateway, particularly for versioned APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API Version Check middleware. This meant that for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Dedicated CORS Middleware

    The PR introduces a new CORSMiddleware struct in mw_cors.go that implements the middleware interface:

    type CORSMiddleware struct {
        *BaseMiddleware
        corsHandler *cors.Cors
    }

    This middleware initializes a CORS handler with the API spec's CORS configuration and handles CORS requests as part of the middleware chain. For preflight OPTIONS requests, it returns early with middleware.StatusRespond to prevent further processing.

    2. Changed Middleware Ordering

    The PR changes where CORS handling occurs in the middleware chain:

    • Before: CORS was applied at the router level using router.Use(c.Handler) in the generateSubRoutes function
    • After: CORS is added to the middleware chain after the Version Check middleware:
      gw.mwAppendEnabled(&chainArray, &VersionCheck{BaseMiddleware: baseMid.Copy()})
      gw.mwAppendEnabled(&chainArray, &CORSMiddleware{BaseMiddleware: baseMid.Copy()})

    This ensures that version-specific CORS configurations are respected since the version check happens first.

    3. OAuth Endpoint Handling

    The PR adds a createCORSWrapper utility function that conditionally applies CORS to OAuth endpoints:

    func createCORSWrapper(spec *APISpec) func(http.HandlerFunc) http.HandlerFunc {
        if !spec.CORS.Enable {
            return func(h http.HandlerFunc) http.HandlerFunc {
                return h
            }
        }
        return func(h http.HandlerFunc) http.HandlerFunc {
            return cors.New(corsConfig(spec)).HandlerFunc(h)
        }
    }

    OAuth endpoints are now wrapped with CORS only when it's enabled for the API, ensuring consistent behavior across all endpoints.

    4. Comprehensive Testing

    The PR includes extensive tests for the new CORS middleware, covering both unit tests and integration tests to verify correct behavior in various scenarios.

    Impact Assessment

    This change ensures that version-specific CORS configurations are properly applied for versioned APIs. The implementation maintains backward compatibility while fixing the issue:

    1. For non-versioned APIs, the behavior remains the same - CORS is still applied, just at a different point in the chain.
    2. For versioned APIs, the correct version-specific CORS configuration will now be used.
    3. OAuth endpoints now consistently respect the API's CORS configuration.

    The PR doesn't introduce any breaking changes to existing behavior outside the ticket description. It simply ensures that CORS checks are performed after API version checks, which is the expected behavior.

    The implementation is clean, well-tested, and follows the established middleware pattern in Tyk, making it maintainable and consistent with the rest of the codebase.


    Tip: Mention me again using /dependency <request>.
    Powered by Probe AI\nTyk Gateway Dependency Impact Reviewer

    Copy link
    Contributor

    CORS Middleware Refactoring Analysis

    This PR addresses an important issue with CORS (Cross-Origin Resource Sharing) handling in the Tyk API Gateway, specifically for versioned OAS APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API Version Check middleware in the chain. This meant that for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Moved CORS Handling from Router Level to Middleware Chain

    Before:

    • CORS was applied at the router level using router.Use(c.Handler) in the generateSubRoutes function
    • This meant CORS was processed before any API-specific middleware, including version checks
    • For versioned APIs, this resulted in always using the base API's CORS configuration

    After:

    • Created a dedicated CORSMiddleware struct that implements the middleware interface
    • Added the CORS middleware to the middleware chain immediately after the VersionCheck middleware
    • This ensures that version-specific CORS configurations are correctly applied

    2. New CORSMiddleware Implementation

    The new CORSMiddleware implementation:

    • Initializes a CORS handler with the API spec's CORS configuration
    • For OPTIONS requests (preflight), it returns early with middleware.StatusRespond if OptionsPassthrough is false
    • For regular requests, it applies CORS headers and continues the middleware chain
    • Properly integrates with the existing middleware architecture

    3. Updated OAuth Endpoint Handling

    • Created a createCORSWrapper utility function that conditionally applies CORS to OAuth endpoints
    • The wrapper only applies CORS when it's enabled for the API
    • This ensures consistent CORS behavior across all API endpoints, including OAuth endpoints

    4. Comprehensive Test Coverage

    • Added unit tests for the CORS middleware functionality
    • Added integration tests for CORS behavior on APIs and OAuth endpoints
    • Tests cover preflight requests, regular requests, and options passthrough scenarios

    Benefits

    1. Correct Version-Specific CORS Handling: The primary issue is fixed - version-specific CORS configurations will now be respected because the CORS middleware executes after the version check.

    2. Consistent CORS Behavior: All endpoints, including OAuth endpoints, now have consistent CORS handling based on the API's configuration.

    3. Better Separation of Concerns: CORS handling is now encapsulated in a dedicated middleware, making the code more maintainable and easier to understand.

    4. Improved Testing: The new tests provide better coverage and validation of CORS behavior.

    This implementation ensures that CORS checks are performed after API version checks, allowing version-specific CORS configurations to be correctly applied. The change maintains backward compatibility while fixing the issue for versioned APIs.


    Tip: Mention me again using /connectivity <request>.
    Powered by Probe AI\nConnectivity Issues Reviewer Prompt for Tyk Gateway

    Copy link
    Contributor

    CORS Middleware Refactoring Analysis

    This PR addresses an important issue with CORS (Cross-Origin Resource Sharing) handling in the Tyk API Gateway, particularly for versioned APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API Version Check middleware. This meant that for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Middleware Execution Order:

      • Previously, CORS was applied at the router level using router.Use(c.Handler) in the generateSubRoutes function, which meant it executed before any API-specific middleware, including version checks.
      • Now, CORS is implemented as a proper middleware (CORSMiddleware) that's inserted into the middleware chain immediately after the VersionCheck middleware.
      • This ensures that version-specific CORS configurations are correctly applied after the API version is determined.
    2. New CORSMiddleware Implementation:

      • A dedicated CORSMiddleware struct was created in mw_cors.go that follows the standard Tyk middleware interface pattern.
      • The middleware initializes a CORS handler with the API spec's CORS configuration.
      • For OPTIONS requests (preflight), it returns early with middleware.StatusRespond if OptionsPassthrough is false.
      • For regular requests, it applies CORS headers and continues the middleware chain.
    3. OAuth Endpoint Handling:

      • OAuth endpoints now use a conditional CORS wrapper via the createCORSWrapper function.
      • This function returns a no-op wrapper when CORS is disabled, ensuring consistent behavior.
      • When CORS is enabled, it properly wraps OAuth endpoints with the appropriate CORS handler.
    4. Comprehensive Testing:

      • Unit tests for the CORS middleware functionality, covering preflight requests, regular requests, and options passthrough.
      • Integration tests that verify CORS behavior on both API endpoints and OAuth endpoints.
      • Tests specifically for versioned APIs to ensure version-specific CORS configurations are correctly applied.

    Benefits

    1. Correct Version-Specific CORS Handling: The primary issue is fixed - version-specific CORS configurations are now respected because the CORS middleware executes after the version check.

    2. Consistent CORS Behavior: All endpoints, including OAuth endpoints, now have consistent CORS handling based on the API's configuration.

    3. Better Separation of Concerns: CORS handling is now encapsulated in a dedicated middleware, making the code more maintainable and easier to understand.

    4. Improved Testing: The new tests provide better coverage and validation of CORS behavior.

    This implementation ensures that CORS checks are performed after API version checks, allowing version-specific CORS configurations to be correctly applied. The change maintains backward compatibility while fixing the issue for versioned APIs.


    Tip: Mention me again using /security <request>.
    Powered by Probe AI\nSecurity Impact Reviewer Prompt

    Copy link
    Contributor

    CORS Middleware Execution Order Fix

    Issue Overview

    This PR addresses an important bug in how CORS (Cross-Origin Resource Sharing) is handled in the Tyk API Gateway, particularly for versioned APIs. The problem was that CORS middleware was being applied at the router level, which meant it executed before the API Version Check middleware in the chain. As a result, for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Removed Router-Level CORS Middleware

    The PR removes the router-level CORS middleware application from the generateSubRoutes function in api_loader.go:

    // Old implementation (removed)
    if spec.CORS.Enable {
        c := cors.New(cors.Options{
            AllowedOrigins:     spec.CORS.AllowedOrigins,
            AllowedMethods:     spec.CORS.AllowedMethods,
            AllowedHeaders:     spec.CORS.AllowedHeaders,
            ExposedHeaders:     spec.CORS.ExposedHeaders,
            AllowCredentials:   spec.CORS.AllowCredentials,
            MaxAge:             spec.CORS.MaxAge,
            OptionsPassthrough: spec.CORS.OptionsPassthrough,
            Debug:              spec.CORS.Debug,
        })
    
        router.Use(c.Handler)
    }

    2. Created Dedicated CORS Middleware

    A new CORSMiddleware struct was implemented in mw_cors.go that follows the standard middleware pattern in Tyk:

    type CORSMiddleware struct {
        *BaseMiddleware
        corsHandler *cors.Cors
    }
    
    func (c *CORSMiddleware) Name() string {
        return "CORSMiddleware"
    }
    
    func (c *CORSMiddleware) EnabledForSpec() bool {
        return c.Spec.CORS.Enable
    }
    
    func (c *CORSMiddleware) Init() {
        c.corsHandler = cors.New(cors.Options{
            AllowedOrigins:     c.Spec.CORS.AllowedOrigins,
            AllowedMethods:     c.Spec.CORS.AllowedMethods,
            AllowedHeaders:     c.Spec.CORS.AllowedHeaders,
            ExposedHeaders:     c.Spec.CORS.ExposedHeaders,
            AllowCredentials:   c.Spec.CORS.AllowCredentials,
            MaxAge:             c.Spec.CORS.MaxAge,
            OptionsPassthrough: c.Spec.CORS.OptionsPassthrough,
            Debug:              c.Spec.CORS.Debug,
        })
    }
    
    func (c *CORSMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
        c.corsHandler.HandlerFunc(w, r)
    
        if r.Method == http.MethodOptions && !c.Spec.CORS.OptionsPassthrough {
            return nil, middleware.StatusRespond
        }
    
        return nil, http.StatusOK
    }

    3. Added CORS Middleware to Chain After Version Check

    The new CORS middleware is now added to the middleware chain immediately after the VersionCheck middleware in api_loader.go:

    if enableVersionCheck {
        chainArray = append(chainArray, gw.createMiddleware(&VersionCheck{BaseMiddleware: &gw.BaseMiddleware}))
    }
    
    if spec.CORS.Enable {
        chainArray = append(chainArray, gw.createMiddleware(&CORSMiddleware{BaseMiddleware: &gw.BaseMiddleware}))
    }

    4. Updated OAuth Endpoint Handlers

    The PR also updates how CORS is applied to OAuth endpoints by creating a createCORSWrapper utility function in server.go that conditionally applies CORS only when it's enabled for the API:

    func createCORSWrapper(spec *APISpec) func(handler http.HandlerFunc) http.HandlerFunc {
        var corsHandler func(http.Handler) http.Handler
    
        if spec.CORS.Enable {
            corsHandler = cors.New(cors.Options{
                AllowedOrigins:     spec.CORS.AllowedOrigins,
                AllowedMethods:     spec.CORS.AllowedMethods,
                AllowedHeaders:     spec.CORS.AllowedHeaders,
                ExposedHeaders:     spec.CORS.ExposedHeaders,
                AllowCredentials:   spec.CORS.AllowCredentials,
                MaxAge:             spec.CORS.MaxAge,
                OptionsPassthrough: spec.CORS.OptionsPassthrough,
                Debug:              spec.CORS.Debug,
            }).Handler
        }
    
        return func(handler http.HandlerFunc) http.HandlerFunc {
            if corsHandler == nil {
                return handler
            }
    
            return func(w http.ResponseWriter, r *http.Request) {
                corsHandler(handler).ServeHTTP(w, r)
            }
        }
    }

    This function is then used to wrap OAuth endpoint handlers:

    wrapWithCORS := createCORSWrapper(spec)
    
    muxer.Handle(apiAuthorizePath, gw.checkIsAPIOwner(allowMethods(oauthHandlers.HandleGenerateAuthCodeData, "POST")))
    muxer.HandleFunc(clientAuthPath, wrapWithCORS(allowMethods(oauthHandlers.HandleAuthorizePassthrough, "GET", "POST")))
    muxer.HandleFunc(clientAccessPath, wrapWithCORS(addSecureAndCacheHeaders(allowMethods(oauthHandlers.HandleAccessRequest, "GET", "POST"))))
    muxer.HandleFunc(revokeToken, wrapWithCORS(oauthHandlers.HandleRevokeToken))
    muxer.HandleFunc(revokeAllTokens, wrapWithCORS(oauthHandlers.HandleRevokeAllTokens))

    5. Added Comprehensive Tests

    The PR adds comprehensive tests for the new CORS middleware in mw_cors_test.go, including:

    • Unit tests for preflight requests, regular requests, and options passthrough
    • Integration tests for CORS behavior on API endpoints and OAuth endpoints

    Benefits and Impact

    1. Correct Version-Specific CORS Handling: The primary issue is fixed - version-specific CORS configurations will now be respected because the CORS middleware executes after the version check.

    2. Consistent CORS Behavior: All endpoints, including OAuth endpoints, now have consistent CORS handling based on the API's configuration.

    3. Better Separation of Concerns: CORS handling is now encapsulated in a dedicated middleware, making the code more maintainable and easier to understand.

    4. Improved Testing: The new tests provide better coverage and validation of CORS behavior.

    Potential Considerations

    1. Header Writing in Non-OPTIONS Requests: As noted in a PR comment, the CORS middleware calls c.corsHandler.HandlerFunc(w, r) for all requests, which might write headers or a response body even for non-OPTIONS requests. This could potentially interfere with subsequent middleware or handlers. A suggested improvement was to use a header-only response writer for non-OPTIONS requests.

    2. Backward Compatibility: The changes maintain backward compatibility for non-versioned APIs while fixing the issue for versioned APIs. The CORS middleware is still applied, just at a different point in the chain.

    Conclusion

    This PR successfully addresses the issue of CORS checks being performed before API version checks by refactoring the CORS handling into a dedicated middleware and positioning it correctly in the middleware chain. The implementation follows Tyk's middleware pattern, maintains backward compatibility, and includes comprehensive tests to ensure correct behavior.


    Tip: Mention me again using /performance <request>.
    Powered by Probe AI\nPerformance Impact Reviewer Prompt

    Copy link
    Contributor

    CORS Middleware Execution Order Fix Analysis

    This PR addresses an important issue with CORS (Cross-Origin Resource Sharing) handling in the Tyk API Gateway, particularly for versioned APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API Version Check middleware in the chain. This meant that for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Moved CORS from Router Level to Middleware Chain

    Before:

    • CORS was applied at the router level using router.Use(c.Handler) in the generateSubRoutes function
    • This meant CORS was processed before any API-specific middleware, including version checks
    • For versioned APIs, this resulted in always using the base API's CORS configuration

    After:

    • Created a dedicated CORSMiddleware struct that implements the middleware interface
    • Added the CORS middleware to the middleware chain immediately after the VersionCheck middleware
    • This ensures that version-specific CORS configurations are correctly applied

    2. New CORSMiddleware Implementation

    The new CORSMiddleware implementation:

    • Initializes a CORS handler with the API spec's CORS configuration
    • For OPTIONS requests (preflight), it returns early with middleware.StatusRespond if OptionsPassthrough is false
    • For regular requests, it applies CORS headers and continues the middleware chain
    • Properly integrates with the existing middleware architecture

    3. Updated OAuth Endpoint Handling

    • Created a createCORSWrapper utility function that conditionally applies CORS to OAuth endpoints
    • The wrapper only applies CORS when it's enabled for the API
    • This ensures consistent CORS behavior across all API endpoints, including OAuth endpoints

    4. Comprehensive Test Coverage

    • Added unit tests for the CORS middleware functionality
    • Added integration tests for CORS behavior on APIs and OAuth endpoints
    • Tests cover preflight requests, regular requests, and options passthrough scenarios

    Benefits

    1. Correct Version-Specific CORS Handling: The primary issue is fixed - version-specific CORS configurations will now be respected because the CORS middleware executes after the version check.

    2. Consistent CORS Behavior: All endpoints, including OAuth endpoints, now have consistent CORS handling based on the API's configuration.

    3. Better Separation of Concerns: CORS handling is now encapsulated in a dedicated middleware, making the code more maintainable and easier to understand.

    4. Improved Testing: The new tests provide better coverage and validation of CORS behavior.

    This implementation ensures that CORS checks are performed after API version checks, allowing version-specific CORS configurations to be correctly applied. The change maintains backward compatibility while fixing the issue for versioned APIs.


    Tip: Mention me again using /dependency <request>.
    Powered by Probe AI\nTyk Gateway Dependency Impact Reviewer

    Copy link
    Contributor

    CORS Middleware Execution Order Fix

    This PR addresses an important issue with CORS (Cross-Origin Resource Sharing) handling in the Tyk API Gateway, particularly for versioned APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API Version Check middleware in the chain. This meant that for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Removed Router-Level CORS Middleware

    The PR removes the router-level CORS middleware application from the generateSubRoutes function in api_loader.go. Previously, CORS was applied using router.Use(c.Handler), which meant it executed before any API-specific middleware, including version checks.

    2. Created Dedicated CORS Middleware

    A new CORSMiddleware struct was implemented in mw_cors.go that follows the standard middleware pattern in Tyk:

    type CORSMiddleware struct {
        *BaseMiddleware
        corsHandler *cors.Cors
    }

    This middleware initializes a CORS handler with the API spec's CORS configuration and handles CORS requests as part of the middleware chain. For preflight OPTIONS requests, it returns early with middleware.StatusRespond to prevent further processing.

    3. Changed Middleware Ordering

    The new CORS middleware is now added to the middleware chain immediately after the VersionCheck middleware:

    gw.mwAppendEnabled(&chainArray, &VersionCheck{BaseMiddleware: baseMid.Copy()})
    gw.mwAppendEnabled(&chainArray, &CORSMiddleware{BaseMiddleware: baseMid.Copy()})

    This ensures that version-specific CORS configurations are respected since the version check happens first.

    4. Updated OAuth Endpoint Handling

    The PR adds a createCORSWrapper utility function that conditionally applies CORS to OAuth endpoints:

    func createCORSWrapper(spec *APISpec) func(http.HandlerFunc) http.HandlerFunc {
        // Only create CORS handler if CORS is enabled
        var corsHandler func(http.Handler) http.Handler
        if spec.CORS.Enable {
            corsHandler = cors.New(cors.Options{...}).Handler
        }
        
        return func(handler http.HandlerFunc) http.HandlerFunc {
            if corsHandler == nil {
                return handler
            }
            return func(w http.ResponseWriter, r *http.Request) {
                corsHandler(handler).ServeHTTP(w, r)
            }
        }
    }

    OAuth endpoints are now wrapped with CORS only when it's enabled for the API, ensuring consistent behavior across all endpoints.

    Benefits

    1. Correct Version-Specific CORS Handling: The primary issue is fixed - version-specific CORS configurations will now be respected because the CORS middleware executes after the version check.

    2. Consistent CORS Behavior: All endpoints, including OAuth endpoints, now have consistent CORS handling based on the API's configuration.

    3. Better Separation of Concerns: CORS handling is now encapsulated in a dedicated middleware, making the code more maintainable and easier to understand.

    4. Improved Testing: The PR includes comprehensive tests for the new CORS middleware, covering both unit tests and integration tests to verify correct behavior in various scenarios.

    This implementation ensures that CORS checks are performed after API version checks, allowing version-specific CORS configurations to be correctly applied. The change maintains backward compatibility while fixing the issue for versioned APIs.


    Tip: Mention me again using /performance <request>.
    Powered by Probe AI\nPerformance Impact Reviewer Prompt

    Copy link
    Contributor

    CORS Middleware Execution Order Fix

    This PR addresses an important issue with CORS (Cross-Origin Resource Sharing) handling in the Tyk API Gateway, particularly for versioned APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API Version Check middleware in the chain. This meant that for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Removed Router-Level CORS Middleware

    The PR removes the router-level CORS middleware application from the generateSubRoutes function in api_loader.go. Previously, CORS was applied using router.Use(c.Handler), which meant it was processed before any API-specific middleware, including version checks.

    2. Created Dedicated CORS Middleware

    A new CORSMiddleware struct was implemented in mw_cors.go that follows the standard middleware pattern in Tyk:

    type CORSMiddleware struct {
        *BaseMiddleware
        corsHandler *cors.Cors
    }
    
    func (c *CORSMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
        c.corsHandler.HandlerFunc(w, r)
    
        if r.Method == http.MethodOptions && !c.Spec.CORS.OptionsPassthrough {
            return nil, middleware.StatusRespond
        }
    
        return nil, http.StatusOK
    }

    3. Changed Middleware Ordering

    The new CORS middleware is now added to the middleware chain immediately after the Version Check middleware:

    gw.mwAppendEnabled(&chainArray, &VersionCheck{BaseMiddleware: baseMid.Copy()})
    gw.mwAppendEnabled(&chainArray, &CORSMiddleware{BaseMiddleware: baseMid.Copy()})

    This ensures that version-specific CORS configurations are respected since the version check happens first.

    4. Updated OAuth Endpoint Handling

    The PR adds a createCORSWrapper utility function that conditionally applies CORS to OAuth endpoints:

    func createCORSWrapper(spec *APISpec) func(handler http.HandlerFunc) http.HandlerFunc {
        // Only create CORS handler if CORS is enabled
        if spec.CORS.Enable {
            // Initialize CORS handler with API's CORS configuration
        }
        
        // Return a wrapper function that either applies CORS or passes through
    }

    OAuth endpoints are now wrapped with CORS only when it's enabled for the API, ensuring consistent behavior across all endpoints.

    5. Comprehensive Testing

    The PR includes extensive tests for the new CORS middleware in mw_cors_test.go, covering:

    • Preflight requests (OPTIONS)
    • Regular requests with CORS headers
    • Options passthrough behavior
    • Unauthorized origin handling
    • Integration tests with actual API configurations

    Benefits

    1. Correct Version-Specific CORS Handling: The primary issue is fixed - version-specific CORS configurations will now be respected because the CORS middleware executes after the version check.

    2. Consistent CORS Behavior: All endpoints, including OAuth endpoints, now have consistent CORS handling based on the API's configuration.

    3. Better Separation of Concerns: CORS handling is now encapsulated in a dedicated middleware, making the code more maintainable and easier to understand.

    4. Improved Testing: The new tests provide better coverage and validation of CORS behavior.

    This implementation ensures that CORS checks are performed after API version checks, allowing version-specific CORS configurations to be correctly applied. The change maintains backward compatibility while fixing the issue for versioned APIs.


    Tip: Mention me again using /connectivity <request>.
    Powered by Probe AI\nConnectivity Issues Reviewer Prompt for Tyk Gateway

    Copy link
    Contributor

    CORS Middleware Execution Order Fix

    Issue Overview

    This PR addresses an important issue with CORS (Cross-Origin Resource Sharing) handling in the Tyk API Gateway, particularly for versioned APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API Version Check middleware in the chain. This meant that for versioned Tyk OAS APIs, the CORS configuration from the base API was always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Removed Router-Level CORS Middleware

    Previously, CORS was applied at the router level in the generateSubRoutes function:

    if spec.CORS.Enable {
        c := cors.New(cors.Options{
            AllowedOrigins:     spec.CORS.AllowedOrigins,
            AllowedMethods:     spec.CORS.AllowedMethods,
            AllowedHeaders:     spec.CORS.AllowedHeaders,
            ExposedHeaders:     spec.CORS.ExposedHeaders,
            AllowCredentials:   spec.CORS.AllowCredentials,
            MaxAge:             spec.CORS.MaxAge,
            OptionsPassthrough: spec.CORS.OptionsPassthrough,
            Debug:              spec.CORS.Debug,
        })
    
        router.Use(c.Handler)
    }

    This code has been completely removed from api_loader.go.

    2. Added Dedicated CORS Middleware

    A new CORSMiddleware struct was created in mw_cors.go that follows the standard middleware pattern in Tyk:

    type CORSMiddleware struct {
        *BaseMiddleware
        corsHandler *cors.Cors
    }
    
    func (c *CORSMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
        c.corsHandler.HandlerFunc(w, r)
    
        if r.Method == http.MethodOptions && !c.Spec.CORS.OptionsPassthrough {
            return nil, middleware.StatusRespond
        }
    
        return nil, http.StatusOK
    }

    This middleware handles CORS preflight requests and applies CORS headers to regular requests. For preflight OPTIONS requests, it returns early with middleware.StatusRespond to prevent further processing if OptionsPassthrough is false.

    3. Changed Middleware Ordering

    The new CORS middleware is now added to the middleware chain after the Version Check middleware:

    if enableVersionCheck {
        chainArray = append(chainArray, gw.createMiddleware(&VersionCheck{BaseMiddleware: baseMid.Copy()}))
    }
    
    if spec.CORS.Enable {
        chainArray = append(chainArray, gw.createMiddleware(&CORSMiddleware{BaseMiddleware: baseMid.Copy()}))
    }

    This ensures that version-specific CORS configurations are respected, as the version check happens first.

    4. Updated OAuth Endpoint Handling

    A createCORSWrapper utility function was added to conditionally apply CORS to OAuth endpoints:

    func createCORSWrapper(spec *APISpec) func(http.HandlerFunc) http.HandlerFunc {
        var corsHandler func(http.Handler) http.Handler
    
        if spec.CORS.Enable {
            corsHandler = cors.New(cors.Options{
                AllowedOrigins:     spec.CORS.AllowedOrigins,
                AllowedMethods:     spec.CORS.AllowedMethods,
                AllowedHeaders:     spec.CORS.AllowedHeaders,
                ExposedHeaders:     spec.CORS.ExposedHeaders,
                AllowCredentials:   spec.CORS.AllowCredentials,
                MaxAge:             spec.CORS.MaxAge,
                OptionsPassthrough: spec.CORS.OptionsPassthrough,
                Debug:              spec.CORS.Debug,
            }).Handler
        }
    
        return func(handler http.HandlerFunc) http.HandlerFunc {
            if corsHandler == nil {
                return handler
            }
    
            return func(w http.ResponseWriter, r *http.Request) {
                corsHandler(handler).ServeHTTP(w, r)
            }
        }
    }

    OAuth endpoints are now wrapped with CORS only when it's enabled for the API:

    wrapWithCORS := createCORSWrapper(spec)
    
    muxer.HandleFunc(clientAuthPath, wrapWithCORS(allowMethods(oauthHandlers.HandleAuthorizePassthrough, "GET", "POST")))
    muxer.HandleFunc(clientAccessPath, wrapWithCORS(addSecureAndCacheHeaders(allowMethods(oauthHandlers.HandleAccessRequest, "GET", "POST"))))
    muxer.HandleFunc(revokeToken, wrapWithCORS(oauthHandlers.HandleRevokeToken))
    muxer.HandleFunc(revokeAllTokens, wrapWithCORS(oauthHandlers.HandleRevokeAllTokens))

    5. Comprehensive Testing

    The PR includes comprehensive tests for the new CORS middleware:

    • Unit tests for preflight requests, regular requests, and options passthrough
    • Tests for unmatched origins to ensure proper handling
    • Integration tests to verify CORS behavior on API endpoints and OAuth endpoints
    • Tests to confirm that CORS headers are only applied when CORS is enabled

    Benefits

    1. Correct Version-Specific CORS Handling: The primary issue is fixed - version-specific CORS configurations will now be respected because the CORS middleware executes after the version check.

    2. Consistent CORS Behavior: All endpoints, including OAuth endpoints, now have consistent CORS handling based on the API's configuration.

    3. Better Separation of Concerns: CORS handling is now encapsulated in a dedicated middleware, making the code more maintainable and easier to understand.

    4. Improved Testing: The new tests provide better coverage and validation of CORS behavior.

    Impact

    This change ensures that CORS checks are performed after API version checks, allowing version-specific CORS configurations to be correctly applied. The implementation maintains backward compatibility while fixing the issue for versioned APIs.

    For non-versioned APIs, the behavior remains the same - CORS is still applied, just at a different point in the chain. For versioned APIs, the correct version-specific CORS configuration will now be used.

    The PR doesn't introduce any breaking changes to existing behavior outside the ticket description. It simply ensures that CORS checks are performed after API version checks, which is the expected behavior.


    Tip: Mention me again using /security <request>.
    Powered by Probe AI\nSecurity Impact Reviewer Prompt

    Copy link
    Contributor

    CORS Middleware Refactoring Analysis

    This PR addresses an important issue with CORS handling in Tyk Gateway, particularly for versioned OAS APIs. The problem was that CORS middleware was being applied at the router level, which executed before the API version check middleware in the chain. This caused version-specific CORS configurations to be ignored, as the base API's CORS configuration was always used regardless of the API version.

    Key Changes

    1. Dedicated CORS Middleware Implementation

    • Created a new CORSMiddleware struct in mw_cors.go that properly implements the middleware interface
    • The middleware initializes a CORS handler with the API's CORS configuration
    • It handles preflight OPTIONS requests appropriately, returning early when needed
    func (c *CORSMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
        c.corsHandler.HandlerFunc(w, r)
    
        if r.Method == http.MethodOptions && !c.Spec.CORS.OptionsPassthrough {
            return nil, middleware.StatusRespond
        }
    
        return nil, http.StatusOK
    }

    2. Middleware Chain Reordering

    • Removed router-level CORS middleware application in api_loader.go
    • Added CORSMiddleware to the middleware chain after the version check:
    gw.mwAppendEnabled(&chainArray, &VersionCheck{BaseMiddleware: baseMid.Copy()})
    gw.mwAppendEnabled(&chainArray, &CORSMiddleware{BaseMiddleware: baseMid.Copy()})

    3. OAuth Endpoint Handling

    • Updated OAuth endpoint handlers in server.go to conditionally apply CORS only when enabled
    • Added a utility function createCORSWrapper for conditional CORS wrapping

    4. Test Improvements

    • Removed outdated CORS tests from api_loader_test.go
    • Added comprehensive unit and integration tests for the new CORS middleware

    Benefits

    1. Correct Version-Specific CORS Handling: The CORS middleware now executes after the version check, ensuring that version-specific CORS configurations are properly applied.

    2. Improved Middleware Chain: The middleware chain is now more logically structured, with CORS handling occurring at the appropriate point in the request lifecycle.

    3. Conditional CORS for OAuth: OAuth endpoints now only apply CORS when it's enabled, reducing unnecessary processing.

    This refactoring ensures that CORS handling works correctly with API versioning, particularly for OAS APIs, allowing API developers to define different CORS configurations for different API versions.


    Tip: Mention me again using /performance <request>.
    Powered by Probe AI\nPerformance Impact Reviewer Prompt

    Copy link
    Contributor

    CORS Middleware Refactoring Analysis

    This PR addresses an important issue with CORS handling in Tyk OAS APIs by moving CORS processing from the router level to a dedicated middleware in the chain.

    Current Implementation Issues

    The current implementation applies CORS middleware at the router level by wrapping the handler:

    // In api_loader.go
    if len(spec.CORS.AllowedOrigins) > 0 {
        c := cors.New(cors.Options{...})
        chainObj.ThisHandler = c.Handler(chainObj.ThisHandler)
    }

    This causes a critical problem: CORS checks execute before the API Version Check middleware, meaning that for versioned Tyk OAS APIs, the CORS configuration from the base API is always used, regardless of any version-specific CORS configurations.

    Solution Overview

    The PR implements these key changes:

    1. Dedicated CORS Middleware: Created a new CORSMiddleware in mw_cors.go that handles CORS as part of the middleware chain

    2. Proper Middleware Order: Positioned CORS middleware after version check in the chain:

      gw.mwAppendEnabled(&chainArray, &VersionCheck{BaseMiddleware: baseMid.Copy()})
      gw.mwAppendEnabled(&chainArray, &CORSMiddleware{BaseMiddleware: baseMid.Copy()})
    3. Conditional OAuth CORS: Updated OAuth endpoint handlers to only apply CORS when enabled

    4. Comprehensive Testing: Added unit and integration tests for the new middleware

    Benefits

    • Version-specific CORS configurations are now correctly applied for OAS APIs
    • CORS handling follows the same middleware pattern as other request processing
    • OPTIONS preflight requests are handled efficiently with early returns
    • Better testability with dedicated middleware tests

    This change ensures that APIs with versioning can have different CORS configurations per version, which is essential for APIs that need to support different cross-origin access patterns across versions.


    Tip: Mention me again using /security <request>.
    Powered by Probe AI\nSecurity Impact Reviewer Prompt

    Copy link
    Contributor

    PR Review: CORS Check Should Be Performed After API Version Check

    This PR addresses an important issue with CORS handling in Tyk OAS APIs. The current implementation applies CORS middleware at the router level, which executes before the API Version Check middleware in the chain. This means that for versioned Tyk OAS APIs, the CORS configuration from the base API is always used, regardless of any version-specific CORS configurations.

    Key Changes

    1. Dedicated CORS Middleware:

      • Created a new CORSMiddleware struct in mw_cors.go that implements the standard middleware interface
      • The middleware uses the rs/cors package to handle CORS requests properly
      • It returns early for preflight OPTIONS requests when OptionsPassthrough is not enabled
    2. Middleware Chain Ordering:

      • Removed the router-level CORS middleware application that was previously applied in api_loader.go
      • Added CORSMiddleware to the middleware chain after the VersionCheck middleware
      • This ensures that version-specific CORS configurations are correctly applied
    3. OAuth Endpoint Handling:

      • Updated OAuth endpoint handlers in server.go to conditionally apply CORS wrapping only when enabled
      • Added a createCORSWrapper utility function that creates a wrapper only if CORS is enabled
    4. Comprehensive Testing:

      • Added unit tests for the new CORSMiddleware implementation
      • Added integration tests that verify CORS behavior for regular APIs, versioned APIs, and OAuth endpoints
      • Tests specifically verify that version-specific CORS configurations are correctly applied

    Technical Analysis

    The core issue was that CORS handling was being applied at the router level before any version-specific context was established. By moving CORS handling into the middleware chain after version checking, the PR ensures that the correct version-specific CORS configuration is used.

    The implementation is clean and follows Tyk's middleware patterns. The CORSMiddleware properly implements the middleware interface with Name(), EnabledForSpec(), Init(), and ProcessRequest() methods. It correctly handles preflight OPTIONS requests by returning early with the appropriate status code.

    The tests are comprehensive and cover various scenarios, including:

    • Basic CORS functionality for regular requests
    • Preflight OPTIONS requests
    • CORS with OptionsPassthrough enabled
    • Version-specific CORS configurations
    • CORS for OAuth endpoints

    Impact and Benefits

    This change ensures that:

    1. Version-specific CORS configurations are correctly applied for OAS APIs
    2. CORS headers are only added when CORS is enabled for the specific API version
    3. OAuth endpoints correctly respect the API's CORS configuration

    The PR maintains backward compatibility while fixing the issue, and the comprehensive test suite ensures the changes work as expected.

    Conclusion

    This is a well-implemented fix for an important issue affecting versioned OAS APIs. The changes are focused, well-tested, and follow Tyk's architectural patterns. The PR should be approved.


    Tip: Mention me again using /connectivity <request>.
    Powered by Probe AI\nConnectivity Issues Reviewer Prompt for Tyk Gateway

    Copy link
    Contributor

    Dependency Impact Review: CORS Middleware Refactoring

    Summary of Changes

    This PR addresses an important issue with CORS handling in Tyk OAS APIs. The current implementation applies CORS middleware at the router level, which executes before the API Version Check middleware. This means that for versioned Tyk OAS APIs, the CORS configuration from the base API is always used, regardless of any version-specific CORS configurations.

    The solution refactors CORS handling into a dedicated middleware that's placed in the middleware chain after the version check, ensuring that version-specific CORS configurations are properly applied.

    Technical Implementation

    The PR makes three key changes:

    1. New CORSMiddleware Implementation:

      • Creates a dedicated CORSMiddleware struct in gateway/mw_cors.go
      • Implements the standard middleware pattern with ProcessRequest method
      • Properly handles preflight OPTIONS requests
    2. Middleware Chain Ordering:

      • Removes router-level CORS middleware application
      • Adds CORSMiddleware to the middleware chain after the version check in api_loader.go
      • This ensures CORS is applied after API version determination
    3. OAuth Endpoint Handling:

      • Updates OAuth endpoint handlers to apply CORS only when enabled
      • Adds createCORSWrapper utility for conditional CORS wrapping

    Test Coverage

    The PR includes comprehensive tests in mw_cors_test.go:

    • Basic CORS functionality tests
    • Tests for versioned API CORS behavior to ensure version-specific configurations are used
    • Tests for OAuth endpoints CORS handling

    Dependency Impact Analysis

    This change has minimal impact on dependencies:

    • No new external dependencies are introduced
    • The PR uses the existing github.com/rs/cors package
    • The implementation follows Tyk's established middleware patterns

    Security Considerations

    The PR maintains the same security properties as the original implementation:

    • CORS headers are still applied based on API configurations
    • No changes to the CORS validation logic itself
    • The change only affects the order of middleware execution

    Performance Impact

    The performance impact should be negligible:

    • CORS processing is moved from router level to middleware chain
    • The same CORS processing logic is used, just at a different point in the request lifecycle
    • No additional processing or memory overhead is introduced

    Conclusion

    This PR correctly addresses the issue of CORS handling for versioned APIs by moving CORS processing from the router level to a dedicated middleware in the chain after version checking. The implementation is clean, well-tested, and follows established patterns in the codebase. The change is focused on fixing a specific issue without introducing unnecessary complexity or dependencies.

    I recommend approving this PR as it properly fixes the issue with minimal risk.


    Tip: Mention me again using /dependency <request>.
    Powered by Probe AI\nTyk Gateway Dependency Impact Reviewer

    Copy link

    @MaciekMis MaciekMis merged commit 714f6d4 into master Jul 17, 2025
    76 of 78 checks passed
    @MaciekMis MaciekMis deleted the TT-10273-oas-cors-check-should-be-performed-after-api-version-check branch July 17, 2025 14:03
    @MaciekMis
    Copy link
    Contributor Author

    /release to release-5.8

    Copy link

    tykbot bot commented Jul 17, 2025

    Working on it! Note that it can take a few minutes.

    tykbot bot pushed a commit that referenced this pull request Jul 17, 2025
    )
    
    ### **User description**
    <details open>
    <summary><a href="https://tyktech.atlassian.net/browse/TT-10273"
    title="TT-10273" target="_blank">TT-10273</a></summary>
      <br />
      <table>
        <tr>
          <th>Summary</th>
    <td>[OAS] CORS check should be performed after API Version check</td>
        </tr>
        <tr>
          <th>Type</th>
          <td>
    <img alt="Bug"
    src="https://tyktech.atlassian.net/rest/api/2/universal_avatar/view/type/issuetype/avatar/10303?size=medium"
    />
            Bug
          </td>
        </tr>
        <tr>
          <th>Status</th>
          <td>In Dev</td>
        </tr>
        <tr>
          <th>Points</th>
          <td>N/A</td>
        </tr>
        <tr>
          <th>Labels</th>
    <td><a
    href="https://tyktech.atlassian.net/issues?jql=project%20%3D%20TT%20AND%20labels%20%3D%20codilime_refined%20ORDER%20BY%20created%20DESC"
    title="codilime_refined">codilime_refined</a></td>
        </tr>
      </table>
    </details>
    <!--
      do not remove this marker as it will break jira-lint's functionality.
      added_by_jira_lint
    -->
    
    ---
    
    <!-- Provide a general summary of your changes in the Title above -->
    
    ## Description
    The current implementation applies CORS middleware at the router level,
    which executes before the API Version Check middleware in the chain.
    This means that for versioned Tyk OAS APIs, the CORS configuration from
    the base API is always used, regardless of any version-specific CORS
    configurations.
    
    ## Related Issue
    
    <!-- This project only accepts pull requests related to open issues. -->
    <!-- If suggesting a new feature or change, please discuss it in an
    issue first. -->
    <!-- If fixing a bug, there should be an issue describing it with steps
    to reproduce. -->
    <!-- OSS: Please link to the issue here. Tyk: please create/link the
    JIRA ticket. -->
    
    ## Motivation and Context
    
    <!-- Why is this change required? What problem does it solve? -->
    
    ## How This Has Been Tested
    
    <!-- Please describe in detail how you tested your changes -->
    <!-- Include details of your testing environment, and the tests -->
    <!-- you ran to see how your change affects other areas of the code,
    etc. -->
    <!-- This information is helpful for reviewers and QA. -->
    
    ## Screenshots (if appropriate)
    
    ## Types of changes
    
    <!-- What types of changes does your code introduce? Put an `x` in all
    the boxes that apply: -->
    
    - [x] Bug fix (non-breaking change which fixes an issue)
    - [ ] New feature (non-breaking change which adds functionality)
    - [ ] Breaking change (fix or feature that would cause existing
    functionality to change)
    - [x] Refactoring or add test (improvements in base code or adds test
    coverage to functionality)
    
    ## Checklist
    
    <!-- Go over all the following points, and put an `x` in all the boxes
    that apply -->
    <!-- If there are no documentation updates required, mark the item as
    checked. -->
    <!-- Raise up any additional concerns not covered by the checklist. -->
    
    - [ ] I ensured that the documentation is up to date
    - [ ] I explained why this PR updates go.mod in detail with reasoning
    why it's required
    - [ ] I would like a code coverage CI quality gate exception and have
    explained why
    
    
    ___
    
    ### **PR Type**
    Bug fix, Enhancement, Tests
    
    
    ___
    
    ### **Description**
    - Refactored CORS handling into a dedicated middleware for correct
    execution order
    
    - Ensured CORS checks occur after API version checks for OAS APIs
    
    - Updated OAuth endpoint handlers to apply CORS only when enabled
    
    - Added comprehensive unit and integration tests for the new CORS
    middleware
    
    
    ___
    
    ### **Changes diagram**
    
    ```mermaid
    flowchart LR
      OldCORS["CORS at router level"] -- "removed" --> X1[""]
      VersionCheck["API Version Check Middleware"] -- "now before" --> NewCORS["CORSMiddleware"]
      NewCORS -- "added to middleware chain" --> APIHandler["API Handler"]
      OAuthEndpoints["OAuth Endpoints"] -- "wrapped with CORS if enabled" --> OAuthCORS["CORS Wrapper"]
      TestsOld["Old CORS tests"] -- "removed" --> X2[""]
      TestsNew["New CORSMiddleware tests"] -- "added" --> CORSMiddleware
    ```
    
    
    ___
    
    
    
    ### **Changes walkthrough** 📝
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader.go</strong><dd><code>Move CORS handling to
    middleware chain after version check</code></dd></summary>
    <hr>
    
    gateway/api_loader.go
    
    <li>Removed router-level CORS middleware application<br> <li> Added
    CORSMiddleware to the middleware chain after version check
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-cdf0b7f176c9d18e1a314b78ddefc2cb3a94b3de66f1f360174692c915734c68">+1/-16</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors.go</strong><dd><code>Add CORSMiddleware
    implementation for CORS handling</code>&nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors.go
    
    <li>Introduced CORSMiddleware struct and logic<br> <li> Handles CORS
    requests as part of middleware chain<br> <li> Returns early for
    preflight OPTIONS requests
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-b83b51e5f6dc341b26ecc1ef7bd72d680f398e599eea327662e2169a3b55f208">+43/-0</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>server.go</strong><dd><code>Apply CORS wrapper to OAuth
    endpoints when enabled</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; </dd></summary>
    <hr>
    
    gateway/server.go
    
    <li>Updated OAuth endpoint handlers to wrap with CORS only if
    enabled<br> <li> Added createCORSWrapper utility for conditional CORS
    wrapping
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-4652d1bf175a0be8f5e61ef7177c9666f23e077d8626b73ac9d13358fa8b525b">+34/-4</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    </table></td></tr><tr><td><strong>Tests</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader_test.go</strong><dd><code>Remove outdated
    CORS tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/api_loader_test.go
    
    - Removed legacy CORS test function
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-f696545a659f4d96421b253edef4bcc8da0e7f52120b8f8866d32cbbb7cc1afc">+0/-73</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors_test.go</strong><dd><code>Add comprehensive
    CORSMiddleware tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors_test.go
    
    <li>Added unit tests for CORSMiddleware logic<br> <li> Added integration
    tests for CORS behavior on APIs and OAuth endpoints<br> <li> Utility
    functions for CORS config and middleware creation
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-60316be235ab2e13eab4b17dfa535b441db3c29d388c433cca7d6fbe4d26c3a0">+157/-0</a>&nbsp;
    </td>
    
    </tr>
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > <details> <summary> Need help?</summary><li>Type <code>/help how to
    ...</code> in the comments thread for any questions about PR-Agent
    usage.</li><li>Check out the <a
    href="https://qodo-merge-docs.qodo.ai/usage-guide/">documentation</a>
    for more information.</li></details>
    
    (cherry picked from commit 714f6d4)
    Copy link

    tykbot bot commented Jul 17, 2025

    @MaciekMis Created merge PRs

    @MaciekMis
    Copy link
    Contributor Author

    /release to release-5.9

    Copy link

    tykbot bot commented Jul 17, 2025

    Working on it! Note that it can take a few minutes.

    tykbot bot pushed a commit that referenced this pull request Jul 17, 2025
    )
    
    ### **User description**
    <details open>
    <summary><a href="https://tyktech.atlassian.net/browse/TT-10273"
    title="TT-10273" target="_blank">TT-10273</a></summary>
      <br />
      <table>
        <tr>
          <th>Summary</th>
    <td>[OAS] CORS check should be performed after API Version check</td>
        </tr>
        <tr>
          <th>Type</th>
          <td>
    <img alt="Bug"
    src="https://tyktech.atlassian.net/rest/api/2/universal_avatar/view/type/issuetype/avatar/10303?size=medium"
    />
            Bug
          </td>
        </tr>
        <tr>
          <th>Status</th>
          <td>In Dev</td>
        </tr>
        <tr>
          <th>Points</th>
          <td>N/A</td>
        </tr>
        <tr>
          <th>Labels</th>
    <td><a
    href="https://tyktech.atlassian.net/issues?jql=project%20%3D%20TT%20AND%20labels%20%3D%20codilime_refined%20ORDER%20BY%20created%20DESC"
    title="codilime_refined">codilime_refined</a></td>
        </tr>
      </table>
    </details>
    <!--
      do not remove this marker as it will break jira-lint's functionality.
      added_by_jira_lint
    -->
    
    ---
    
    <!-- Provide a general summary of your changes in the Title above -->
    
    ## Description
    The current implementation applies CORS middleware at the router level,
    which executes before the API Version Check middleware in the chain.
    This means that for versioned Tyk OAS APIs, the CORS configuration from
    the base API is always used, regardless of any version-specific CORS
    configurations.
    
    ## Related Issue
    
    <!-- This project only accepts pull requests related to open issues. -->
    <!-- If suggesting a new feature or change, please discuss it in an
    issue first. -->
    <!-- If fixing a bug, there should be an issue describing it with steps
    to reproduce. -->
    <!-- OSS: Please link to the issue here. Tyk: please create/link the
    JIRA ticket. -->
    
    ## Motivation and Context
    
    <!-- Why is this change required? What problem does it solve? -->
    
    ## How This Has Been Tested
    
    <!-- Please describe in detail how you tested your changes -->
    <!-- Include details of your testing environment, and the tests -->
    <!-- you ran to see how your change affects other areas of the code,
    etc. -->
    <!-- This information is helpful for reviewers and QA. -->
    
    ## Screenshots (if appropriate)
    
    ## Types of changes
    
    <!-- What types of changes does your code introduce? Put an `x` in all
    the boxes that apply: -->
    
    - [x] Bug fix (non-breaking change which fixes an issue)
    - [ ] New feature (non-breaking change which adds functionality)
    - [ ] Breaking change (fix or feature that would cause existing
    functionality to change)
    - [x] Refactoring or add test (improvements in base code or adds test
    coverage to functionality)
    
    ## Checklist
    
    <!-- Go over all the following points, and put an `x` in all the boxes
    that apply -->
    <!-- If there are no documentation updates required, mark the item as
    checked. -->
    <!-- Raise up any additional concerns not covered by the checklist. -->
    
    - [ ] I ensured that the documentation is up to date
    - [ ] I explained why this PR updates go.mod in detail with reasoning
    why it's required
    - [ ] I would like a code coverage CI quality gate exception and have
    explained why
    
    
    ___
    
    ### **PR Type**
    Bug fix, Enhancement, Tests
    
    
    ___
    
    ### **Description**
    - Refactored CORS handling into a dedicated middleware for correct
    execution order
    
    - Ensured CORS checks occur after API version checks for OAS APIs
    
    - Updated OAuth endpoint handlers to apply CORS only when enabled
    
    - Added comprehensive unit and integration tests for the new CORS
    middleware
    
    
    ___
    
    ### **Changes diagram**
    
    ```mermaid
    flowchart LR
      OldCORS["CORS at router level"] -- "removed" --> X1[""]
      VersionCheck["API Version Check Middleware"] -- "now before" --> NewCORS["CORSMiddleware"]
      NewCORS -- "added to middleware chain" --> APIHandler["API Handler"]
      OAuthEndpoints["OAuth Endpoints"] -- "wrapped with CORS if enabled" --> OAuthCORS["CORS Wrapper"]
      TestsOld["Old CORS tests"] -- "removed" --> X2[""]
      TestsNew["New CORSMiddleware tests"] -- "added" --> CORSMiddleware
    ```
    
    
    ___
    
    
    
    ### **Changes walkthrough** 📝
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader.go</strong><dd><code>Move CORS handling to
    middleware chain after version check</code></dd></summary>
    <hr>
    
    gateway/api_loader.go
    
    <li>Removed router-level CORS middleware application<br> <li> Added
    CORSMiddleware to the middleware chain after version check
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-cdf0b7f176c9d18e1a314b78ddefc2cb3a94b3de66f1f360174692c915734c68">+1/-16</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors.go</strong><dd><code>Add CORSMiddleware
    implementation for CORS handling</code>&nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors.go
    
    <li>Introduced CORSMiddleware struct and logic<br> <li> Handles CORS
    requests as part of middleware chain<br> <li> Returns early for
    preflight OPTIONS requests
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-b83b51e5f6dc341b26ecc1ef7bd72d680f398e599eea327662e2169a3b55f208">+43/-0</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>server.go</strong><dd><code>Apply CORS wrapper to OAuth
    endpoints when enabled</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; </dd></summary>
    <hr>
    
    gateway/server.go
    
    <li>Updated OAuth endpoint handlers to wrap with CORS only if
    enabled<br> <li> Added createCORSWrapper utility for conditional CORS
    wrapping
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-4652d1bf175a0be8f5e61ef7177c9666f23e077d8626b73ac9d13358fa8b525b">+34/-4</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    </table></td></tr><tr><td><strong>Tests</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader_test.go</strong><dd><code>Remove outdated
    CORS tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/api_loader_test.go
    
    - Removed legacy CORS test function
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-f696545a659f4d96421b253edef4bcc8da0e7f52120b8f8866d32cbbb7cc1afc">+0/-73</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors_test.go</strong><dd><code>Add comprehensive
    CORSMiddleware tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors_test.go
    
    <li>Added unit tests for CORSMiddleware logic<br> <li> Added integration
    tests for CORS behavior on APIs and OAuth endpoints<br> <li> Utility
    functions for CORS config and middleware creation
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-60316be235ab2e13eab4b17dfa535b441db3c29d388c433cca7d6fbe4d26c3a0">+157/-0</a>&nbsp;
    </td>
    
    </tr>
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > <details> <summary> Need help?</summary><li>Type <code>/help how to
    ...</code> in the comments thread for any questions about PR-Agent
    usage.</li><li>Check out the <a
    href="https://qodo-merge-docs.qodo.ai/usage-guide/">documentation</a>
    for more information.</li></details>
    
    (cherry picked from commit 714f6d4)
    Copy link

    tykbot bot commented Jul 17, 2025

    @MaciekMis Seems like there is conflict and it require manual merge.

    buger added a commit that referenced this pull request Jul 17, 2025
    …er API Version check (#7179)
    
    [TT-10273] CORS check should be performed after API Version check (#7179)
    
    ### **User description**
    <details open>
    <summary><a href="https://tyktech.atlassian.net/browse/TT-10273"
    title="TT-10273" target="_blank">TT-10273</a></summary>
      <br />
      <table>
        <tr>
          <th>Summary</th>
    <td>[OAS] CORS check should be performed after API Version check</td>
        </tr>
        <tr>
          <th>Type</th>
          <td>
    <img alt="Bug"
    src="https://tyktech.atlassian.net/rest/api/2/universal_avatar/view/type/issuetype/avatar/10303?size=medium"
    />
            Bug
          </td>
        </tr>
        <tr>
          <th>Status</th>
          <td>In Dev</td>
        </tr>
        <tr>
          <th>Points</th>
          <td>N/A</td>
        </tr>
        <tr>
          <th>Labels</th>
    <td><a
    href="https://tyktech.atlassian.net/issues?jql=project%20%3D%20TT%20AND%20labels%20%3D%20codilime_refined%20ORDER%20BY%20created%20DESC"
    title="codilime_refined">codilime_refined</a></td>
        </tr>
      </table>
    </details>
    <!--
      do not remove this marker as it will break jira-lint's functionality.
      added_by_jira_lint
    -->
    
    ---
    
    <!-- Provide a general summary of your changes in the Title above -->
    
    ## Description
    The current implementation applies CORS middleware at the router level,
    which executes before the API Version Check middleware in the chain.
    This means that for versioned Tyk OAS APIs, the CORS configuration from
    the base API is always used, regardless of any version-specific CORS
    configurations.
    
    ## Related Issue
    
    <!-- This project only accepts pull requests related to open issues. -->
    <!-- If suggesting a new feature or change, please discuss it in an
    issue first. -->
    <!-- If fixing a bug, there should be an issue describing it with steps
    to reproduce. -->
    <!-- OSS: Please link to the issue here. Tyk: please create/link the
    JIRA ticket. -->
    
    ## Motivation and Context
    
    <!-- Why is this change required? What problem does it solve? -->
    
    ## How This Has Been Tested
    
    <!-- Please describe in detail how you tested your changes -->
    <!-- Include details of your testing environment, and the tests -->
    <!-- you ran to see how your change affects other areas of the code,
    etc. -->
    <!-- This information is helpful for reviewers and QA. -->
    
    ## Screenshots (if appropriate)
    
    ## Types of changes
    
    <!-- What types of changes does your code introduce? Put an `x` in all
    the boxes that apply: -->
    
    - [x] Bug fix (non-breaking change which fixes an issue)
    - [ ] New feature (non-breaking change which adds functionality)
    - [ ] Breaking change (fix or feature that would cause existing
    functionality to change)
    - [x] Refactoring or add test (improvements in base code or adds test
    coverage to functionality)
    
    ## Checklist
    
    <!-- Go over all the following points, and put an `x` in all the boxes
    that apply -->
    <!-- If there are no documentation updates required, mark the item as
    checked. -->
    <!-- Raise up any additional concerns not covered by the checklist. -->
    
    - [ ] I ensured that the documentation is up to date
    - [ ] I explained why this PR updates go.mod in detail with reasoning
    why it's required
    - [ ] I would like a code coverage CI quality gate exception and have
    explained why
    
    
    ___
    
    ### **PR Type**
    Bug fix, Enhancement, Tests
    
    
    ___
    
    ### **Description**
    - Refactored CORS handling into a dedicated middleware for correct
    execution order
    
    - Ensured CORS checks occur after API version checks for OAS APIs
    
    - Updated OAuth endpoint handlers to apply CORS only when enabled
    
    - Added comprehensive unit and integration tests for the new CORS
    middleware
    
    
    ___
    
    ### **Changes diagram**
    
    ```mermaid
    flowchart LR
      OldCORS["CORS at router level"] -- "removed" --> X1[""]
      VersionCheck["API Version Check Middleware"] -- "now before" --> NewCORS["CORSMiddleware"]
      NewCORS -- "added to middleware chain" --> APIHandler["API Handler"]
      OAuthEndpoints["OAuth Endpoints"] -- "wrapped with CORS if enabled" --> OAuthCORS["CORS Wrapper"]
      TestsOld["Old CORS tests"] -- "removed" --> X2[""]
      TestsNew["New CORSMiddleware tests"] -- "added" --> CORSMiddleware
    ```
    
    
    ___
    
    
    
    ### **Changes walkthrough** 📝
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader.go</strong><dd><code>Move CORS handling to
    middleware chain after version check</code></dd></summary>
    <hr>
    
    gateway/api_loader.go
    
    <li>Removed router-level CORS middleware application<br> <li> Added
    CORSMiddleware to the middleware chain after version check
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-cdf0b7f176c9d18e1a314b78ddefc2cb3a94b3de66f1f360174692c915734c68">+1/-16</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors.go</strong><dd><code>Add CORSMiddleware
    implementation for CORS handling</code>&nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors.go
    
    <li>Introduced CORSMiddleware struct and logic<br> <li> Handles CORS
    requests as part of middleware chain<br> <li> Returns early for
    preflight OPTIONS requests
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-b83b51e5f6dc341b26ecc1ef7bd72d680f398e599eea327662e2169a3b55f208">+43/-0</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>server.go</strong><dd><code>Apply CORS wrapper to OAuth
    endpoints when enabled</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; </dd></summary>
    <hr>
    
    gateway/server.go
    
    <li>Updated OAuth endpoint handlers to wrap with CORS only if
    enabled<br> <li> Added createCORSWrapper utility for conditional CORS
    wrapping
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-4652d1bf175a0be8f5e61ef7177c9666f23e077d8626b73ac9d13358fa8b525b">+34/-4</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    </table></td></tr><tr><td><strong>Tests</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader_test.go</strong><dd><code>Remove outdated
    CORS tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/api_loader_test.go
    
    - Removed legacy CORS test function
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-f696545a659f4d96421b253edef4bcc8da0e7f52120b8f8866d32cbbb7cc1afc">+0/-73</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors_test.go</strong><dd><code>Add comprehensive
    CORSMiddleware tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors_test.go
    
    <li>Added unit tests for CORSMiddleware logic<br> <li> Added integration
    tests for CORS behavior on APIs and OAuth endpoints<br> <li> Utility
    functions for CORS config and middleware creation
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-60316be235ab2e13eab4b17dfa535b441db3c29d388c433cca7d6fbe4d26c3a0">+157/-0</a>&nbsp;
    </td>
    
    </tr>
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > <details> <summary> Need help?</summary><li>Type <code>/help how to
    ...</code> in the comments thread for any questions about PR-Agent
    usage.</li><li>Check out the <a
    href="https://qodo-merge-docs.qodo.ai/usage-guide/">documentation</a>
    for more information.</li></details>
    MaciekMis added a commit that referenced this pull request Jul 17, 2025
    …er API Version check (#7179) (#7242)
    
    ### **User description**
    [TT-10273] CORS check should be performed after API Version check
    (#7179)
    
    ### **User description**
    <details open>
    <summary><a href="https://tyktech.atlassian.net/browse/TT-10273"
    title="TT-10273" target="_blank">TT-10273</a></summary>
      <br />
      <table>
        <tr>
          <th>Summary</th>
    <td>[OAS] CORS check should be performed after API Version check</td>
        </tr>
        <tr>
          <th>Type</th>
          <td>
    <img alt="Bug"
    
    src="https://tyktech.atlassian.net/rest/api/2/universal_avatar/view/type/issuetype/avatar/10303?size=medium"
    />
            Bug
          </td>
        </tr>
        <tr>
          <th>Status</th>
          <td>In Dev</td>
        </tr>
        <tr>
          <th>Points</th>
          <td>N/A</td>
        </tr>
        <tr>
          <th>Labels</th>
    <td><a
    
    href="https://tyktech.atlassian.net/issues?jql=project%20%3D%20TT%20AND%20labels%20%3D%20codilime_refined%20ORDER%20BY%20created%20DESC"
    title="codilime_refined">codilime_refined</a></td>
        </tr>
      </table>
    </details>
    <!--
      do not remove this marker as it will break jira-lint's functionality.
      added_by_jira_lint
    -->
    
    ---
    
    <!-- Provide a general summary of your changes in the Title above -->
    
    ## Description
    The current implementation applies CORS middleware at the router level,
    which executes before the API Version Check middleware in the chain.
    This means that for versioned Tyk OAS APIs, the CORS configuration from
    the base API is always used, regardless of any version-specific CORS
    configurations.
    
    ## Related Issue
    
    <!-- This project only accepts pull requests related to open issues. -->
    <!-- If suggesting a new feature or change, please discuss it in an
    issue first. -->
    <!-- If fixing a bug, there should be an issue describing it with steps
    to reproduce. -->
    <!-- OSS: Please link to the issue here. Tyk: please create/link the
    JIRA ticket. -->
    
    ## Motivation and Context
    
    <!-- Why is this change required? What problem does it solve? -->
    
    ## How This Has Been Tested
    
    <!-- Please describe in detail how you tested your changes -->
    <!-- Include details of your testing environment, and the tests -->
    <!-- you ran to see how your change affects other areas of the code,
    etc. -->
    <!-- This information is helpful for reviewers and QA. -->
    
    ## Screenshots (if appropriate)
    
    ## Types of changes
    
    <!-- What types of changes does your code introduce? Put an `x` in all
    the boxes that apply: -->
    
    - [x] Bug fix (non-breaking change which fixes an issue)
    - [ ] New feature (non-breaking change which adds functionality)
    - [ ] Breaking change (fix or feature that would cause existing
    functionality to change)
    - [x] Refactoring or add test (improvements in base code or adds test
    coverage to functionality)
    
    ## Checklist
    
    <!-- Go over all the following points, and put an `x` in all the boxes
    that apply -->
    <!-- If there are no documentation updates required, mark the item as
    checked. -->
    <!-- Raise up any additional concerns not covered by the checklist. -->
    
    - [ ] I ensured that the documentation is up to date
    - [ ] I explained why this PR updates go.mod in detail with reasoning
    why it's required
    - [ ] I would like a code coverage CI quality gate exception and have
    explained why
    
    
    ___
    
    ### **PR Type**
    Bug fix, Enhancement, Tests
    
    
    ___
    
    ### **Description**
    - Refactored CORS handling into a dedicated middleware for correct
    execution order
    
    - Ensured CORS checks occur after API version checks for OAS APIs
    
    - Updated OAuth endpoint handlers to apply CORS only when enabled
    
    - Added comprehensive unit and integration tests for the new CORS
    middleware
    
    
    ___
    
    ### **Changes diagram**
    
    ```mermaid
    flowchart LR
      OldCORS["CORS at router level"] -- "removed" --> X1[""]
      VersionCheck["API Version Check Middleware"] -- "now before" --> NewCORS["CORSMiddleware"]
      NewCORS -- "added to middleware chain" --> APIHandler["API Handler"]
      OAuthEndpoints["OAuth Endpoints"] -- "wrapped with CORS if enabled" --> OAuthCORS["CORS Wrapper"]
      TestsOld["Old CORS tests"] -- "removed" --> X2[""]
      TestsNew["New CORSMiddleware tests"] -- "added" --> CORSMiddleware
    ```
    
    
    ___
    
    
    
    ### **Changes walkthrough** 📝
    <table><thead><tr><th></th><th align="left">Relevant
    
    files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader.go</strong><dd><code>Move CORS handling to
    middleware chain after version check</code></dd></summary>
    <hr>
    
    gateway/api_loader.go
    
    <li>Removed router-level CORS middleware application<br> <li> Added
    CORSMiddleware to the middleware chain after version check
    
    
    </details>
    
    
      </td>
    <td><a
    
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-cdf0b7f176c9d18e1a314b78ddefc2cb3a94b3de66f1f360174692c915734c68">+1/-16</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors.go</strong><dd><code>Add CORSMiddleware
    implementation for CORS handling</code>&nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors.go
    
    <li>Introduced CORSMiddleware struct and logic<br> <li> Handles CORS
    requests as part of middleware chain<br> <li> Returns early for
    preflight OPTIONS requests
    
    
    </details>
    
    
      </td>
    <td><a
    
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-b83b51e5f6dc341b26ecc1ef7bd72d680f398e599eea327662e2169a3b55f208">+43/-0</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>server.go</strong><dd><code>Apply CORS wrapper to OAuth
    endpoints when enabled</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; </dd></summary>
    <hr>
    
    gateway/server.go
    
    <li>Updated OAuth endpoint handlers to wrap with CORS only if
    enabled<br> <li> Added createCORSWrapper utility for conditional CORS
    wrapping
    
    
    </details>
    
    
      </td>
    <td><a
    
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-4652d1bf175a0be8f5e61ef7177c9666f23e077d8626b73ac9d13358fa8b525b">+34/-4</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    </table></td></tr><tr><td><strong>Tests</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader_test.go</strong><dd><code>Remove outdated
    CORS tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/api_loader_test.go
    
    - Removed legacy CORS test function
    
    
    </details>
    
    
      </td>
    <td><a
    
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-f696545a659f4d96421b253edef4bcc8da0e7f52120b8f8866d32cbbb7cc1afc">+0/-73</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors_test.go</strong><dd><code>Add comprehensive
    CORSMiddleware tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors_test.go
    
    <li>Added unit tests for CORSMiddleware logic<br> <li> Added integration
    tests for CORS behavior on APIs and OAuth endpoints<br> <li> Utility
    functions for CORS config and middleware creation
    
    
    </details>
    
    
      </td>
    <td><a
    
    href="https://github.com/TykTechnologies/tyk/pull/7179/files#diff-60316be235ab2e13eab4b17dfa535b441db3c29d388c433cca7d6fbe4d26c3a0">+157/-0</a>&nbsp;
    </td>
    
    </tr>
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > <details> <summary> Need help?</summary><li>Type <code>/help how to
    ...</code> in the comments thread for any questions about PR-Agent
    usage.</li><li>Check out the <a
    href="https://qodo-merge-docs.qodo.ai/usage-guide/">documentation</a>
    for more information.</li></details>
    
    [TT-10273]:
    https://tyktech.atlassian.net/browse/TT-10273?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    
    ___
    
    ### **PR Type**
    Bug fix, Enhancement, Tests
    
    
    ___
    
    ### **Description**
    - Refactored CORS handling into a dedicated middleware after version
    check
    
    - Ensured CORS checks use version-specific configuration for OAS APIs
    
    - Updated OAuth endpoint handlers to conditionally apply CORS
    
    - Added comprehensive unit and integration tests for new CORS middleware
    
    
    ___
    
    ### **Changes diagram**
    
    ```mermaid
    flowchart LR
      OldCORS["CORS at router level"] -- "removed" --> X1[""]
      VersionCheck["API Version Check Middleware"] -- "now before" --> NewCORS["CORSMiddleware"]
      NewCORS -- "added to middleware chain" --> APIHandler["API Handler"]
      OAuthEndpoints["OAuth Endpoints"] -- "wrapped with CORS if enabled" --> OAuthCORS["CORS Wrapper"]
      TestsOld["Old CORS tests"] -- "removed" --> X2[""]
      TestsNew["New CORSMiddleware tests"] -- "added" --> CORSMiddleware
    ```
    
    
    ___
    
    
    
    ### **Changes walkthrough** 📝
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader.go</strong><dd><code>Move CORS handling to
    middleware chain after version check</code></dd></summary>
    <hr>
    
    gateway/api_loader.go
    
    <li>Removed router-level CORS middleware application<br> <li> Added
    CORSMiddleware to middleware chain after version check
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7242/files#diff-cdf0b7f176c9d18e1a314b78ddefc2cb3a94b3de66f1f360174692c915734c68">+1/-16</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors.go</strong><dd><code>Add CORSMiddleware
    implementation for CORS handling</code>&nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors.go
    
    <li>Introduced CORSMiddleware struct and logic<br> <li> Handles CORS
    requests as part of middleware chain<br> <li> Returns early for
    preflight OPTIONS requests
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7242/files#diff-b83b51e5f6dc341b26ecc1ef7bd72d680f398e599eea327662e2169a3b55f208">+43/-0</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>server.go</strong><dd><code>Apply CORS wrapper to OAuth
    endpoints when enabled</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; </dd></summary>
    <hr>
    
    gateway/server.go
    
    <li>Updated OAuth endpoint handlers to wrap with CORS only if
    enabled<br> <li> Added createCORSWrapper utility for conditional CORS
    wrapping
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7242/files#diff-4652d1bf175a0be8f5e61ef7177c9666f23e077d8626b73ac9d13358fa8b525b">+34/-4</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    </table></td></tr><tr><td><strong>Tests</strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>api_loader_test.go</strong><dd><code>Remove outdated
    CORS tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/api_loader_test.go
    
    - Removed legacy CORS test function
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7242/files#diff-f696545a659f4d96421b253edef4bcc8da0e7f52120b8f8866d32cbbb7cc1afc">+0/-73</a>&nbsp;
    &nbsp; </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>mw_cors_test.go</strong><dd><code>Add comprehensive
    CORSMiddleware tests</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; </dd></summary>
    <hr>
    
    gateway/mw_cors_test.go
    
    <li>Added unit tests for CORSMiddleware logic<br> <li> Added integration
    tests for CORS behavior on APIs and OAuth endpoints<br> <li> Utility
    functions for CORS config and middleware creation
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7242/files#diff-60316be235ab2e13eab4b17dfa535b441db3c29d388c433cca7d6fbe4d26c3a0">+187/-0</a>&nbsp;
    </td>
    
    </tr>
    
    <tr>
      <td>
        <details>
    <summary><strong>reverse_proxy_test.go</strong><dd><code>Remove CORS
    header checks from GraphQL passthrough test</code>&nbsp; &nbsp;
    </dd></summary>
    <hr>
    
    gateway/reverse_proxy_test.go
    
    <li>Removed CORS header assertions from GraphQL options passthrough test
    
    
    </details>
    
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/7242/files#diff-ce040f6555143f760fba6059744bc600b6954f0966dfb0fa2832b5eabf7a3c3f">+0/-5</a>&nbsp;
    &nbsp; &nbsp; </td>
    
    </tr>
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > <details> <summary> Need help?</summary><li>Type <code>/help how to
    ...</code> in the comments thread for any questions about PR-Agent
    usage.</li><li>Check out the <a
    href="https://qodo-merge-docs.qodo.ai/usage-guide/">documentation</a>
    for more information.</li></details>
    
    Co-authored-by: Maciej Miś <[email protected]>
    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.

    4 participants