Skip to content

Cors OData Preflight #208

Closed
Closed

Description

@LianwMS

When the browser sends an "OPTIONS" pre-flight request for an OData endpoint, the response may be a 500 error when it should not be.

A simple "Get" action on an Cors attributed ODataController like the following will succeed:

[EnableCors(origins: "http://localhost:52135", headers: "*", methods: "*")]
public class SampleController : ODataController
{
    [EnableQuery]
        public IQueryable<JobDTO> Get()
        {... }

However a call to an action in the same controller with a "delete" verb and an argument like this fails:

public async Task<IHttpActionResult> Delete([FromODataUri] Guid key)
        {...}

Sample Error Message:

{
"error":{
"code":"","message":"An error has occurred.","innererror":{
  "message":"Object reference not set to an instance of an object.","type":
"System.NullReferenceException","stacktrace":" 
at 
System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.Create405Response(HttpControllerContext controllerContext, IEnumerable1 allowedCandidates)\r\n 
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.CreateSelectionError(HttpControllerContext controllerContext)\r\n 
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n 
at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n 
at System.Web.Http.Tracing.Tracers.HttpActionSelectorTracer.<>c__DisplayClass2.<System.Web.Http.Controllers.IHttpActionSelector.SelectAction>b__0()\r\n 
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action1 beginTrace, Action execute, Action1 endTrace, Action1 errorTrace)\r\n 
at System.Web.Http.Tracing.Tracers.HttpActionSelectorTracer.System.Web.Http.Controllers.IHttpActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n 
at System.Web.OData.Routing.ODataActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n 
at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.SelectAction(HttpRequestMessage request, IHttpRouteData routeData, HttpConfiguration config)\r\n 
at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider(HttpRequestMessage request)\r\n 
at System.Web.Http.Cors.Tracing.CorsPolicyProviderFactoryTracer.<>c__DisplayClass3.<GetCorsPolicyProvider>b__1()\r\n 
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action1 beginTrace, Action execute, Action1 endTrace, Action1 errorTrace)\r\n 
at System.Web.Http.Cors.Tracing.CorsPolicyProviderFactoryTracer.GetCorsPolicyProvider(HttpRequestMessage request)\r\n at System.Web.Http.Cors.CorsMessageHandler.<GetCorsPolicyAsync>d__10.MoveNext() 
\r\n--- End of stack trace from previous location where exception was thrown ---\r\n 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n 
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n 
at System.Web.Http.Cors.CorsMessageHandler.<HandleCorsPreflightRequestAsync>d__b.MoveNext()\r\n--- 
End of stack trace from previous location where exception was thrown ---\r\n 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n 
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at 
System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0.MoveNext()"
}
} 
}

To summarize where this appears to be going wrong:

  IHttpRouteData routeData = config.Routes.GetRouteData(request);
                    if (routeData == null)
                    {
                        // No route data found for selecting action with EnableCorsAttribute, thus no ICorsPolicyProvider is returned
                        // and let the CorsMessageHandler flow the request to the normal Web API pipeline.
                        return null;
                    }

                    actionDescriptor = SelectAction(targetRequest, routeData, config);
  1. When GetRouteData(request) is called it has side-effects on the request object it is passed (particularly for an Odata route).
  2. There is a later dependency on those side-effects in the SelectAction() implementation (particularly for an Odata route).
  3. IFF the expected side-effects are not present\observed the action selection logic “falls-back” (incorrectly)to simple WebApi selection semantics.

It would seem (to a naive observer) that simply sending the same "targetRequest" through both calls would resolve this troubling issue. Can someone who is more familiar please have a look and tell me if this is a bug or whether I may be doing something wrong? Obviously I think "success" should be defined as a fully functional OData service protected by attribute based Cors.

From: Coldplex 2231

Activity

  1. added this to the milestone on Feb 10, 2015
  2. modified the milestones: , on Mar 26, 2015
  3. modified the milestones: , on May 27, 2015
  4. modified the milestones: v5.8, v5.7 on Jul 2, 2015
  5. modified the milestones: v5.9, v5.8 on Jan 6, 2016
  6. modified the milestones: v5.10, v5.9 on Mar 21, 2016
  7. xmichaelx commented on Jun 15, 2016

    @xmichaelx

    I have exactly the same issue, DELETE fails on the preflight OPTIONS request. At the level of:

    System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.CreateSelectionError(HttpControllerContext controllerContext)

    It is determined that no suitable handler was found for preflight OPTIONS preflight request and there should be 404 or 405 send as a response, but something is null and 500 is thrown instead.

    And here it goes return base.SelectAction(controllerContext);:

    public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
    {
        if (controllerContext.RouteData.Route == controllerContext.Configuration.Routes[ODataRouteNames.PropertyNavigation])
        {
            // remove any trailing () that might have been picked up by the Routing, this avoid us having to 
            // specify two routes, with/without the trailing ().
            string navigationProperty = controllerContext.RouteData.Values["navigationProperty"].ToString();
            navigationProperty = navigationProperty.Replace("()", string.Empty);
    
            if (controllerContext.Request.Method == HttpMethod.Get)
            {
                // pick the Action with the name GetNavigationProperty
                controllerContext.RouteData.Values.Add("Action", String.Format("Get{0}", navigationProperty));
            }
            else if (controllerContext.Request.Method == HttpMethod.Put)
            {
                controllerContext.RouteData.Values.Add("Action", String.Format("Put{0}", navigationProperty));
            }
            else if (controllerContext.Request.Method == HttpMethod.Post)
            {
                controllerContext.RouteData.Values.Add("Action", String.Format("Post{0}", navigationProperty));
            }
        }
    
        return base.SelectAction(controllerContext);
    }

    Currently I have a workaround that redirects OPTIONS requests to my odata by adding an additional step in the pipeline before the controller is called, but it's ugly. Please fix this :)

  8. lyweiwei commented on Sep 1, 2016

    @lyweiwei

    How's it going on this issue? It has been opened for 1.5 year, and seems it still repros on the sample services.

  9. bkwdesign commented on Dec 21, 2017

    @bkwdesign

    I think I'm encountering a somewhat related issue when trying to escape special characters in my OData 'action'..

    For example:
    this request, which performs a search on 'fruit' works:
    /odata/Search(searchterm = 'fruit')?$count=true&$expand=ThingType,Status,Location

    this request, which must be escaped, because I want to search 'A&D' fails:
    /odata/Search(searchterm = 'A%26D')?$count=true&$expand=ThingType,Status,Location

    Firefox console output says:
    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:64810/odata/Search(searchterm%20=%20'A%26D')?$count=true&$expand=ThingType,Status,Location,WorkOrderLinks($orderby=LinkAddedTime%20asc;$top=1). (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

    When I look at the actual OPTIONS request, it says 400 Bad Request .. at first, I thought my jQuery ajax layer is interpreting the escaped characters when I don't want it to. But when I do an F11 step through of the code, that is not the case.

  10. bitsforthought commented on Sep 9, 2018

    @bitsforthought
    Contributor

    I've just independently encountered this issue (with a slightly different failure mode) when experimenting with the CORS implementation in Azure Search. Along the way, I've come up with a reliable repro and a possible workaround.

    First, the repro. This is using Microsoft.AspNet.OData 7.0.1. There is a similar problem using Microsoft.AspNetCore.OData with CORS, but I filed a separate issue for that since the mechanics of CORS has changed quite a bit between ASP.NET and ASP.NET Core.

    The repro can be found here

    Here is the output from the failing test:

    Test Name:	MakeCorsODataRequestExpectSuccess
    Test Outcome:	Failed
    Result Message:	Assert.AreEqual failed. Expected:<OK>. Actual:<InternalServerError>. Expected matching statuses for request OPTIONS http://localhost:9999/odata/Indexes
    Result StandardOutput:
    {"error":{"code":"","message":"An error has occurred.","innererror":{"message":"Multiple actions were found that match the request:
    Get on type ODataAndCorsClassic.IndexesController
    DoSomething on type ODataAndCorsClassic.IndexesController","type":"System.InvalidOperationException",
    "stacktrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)
       at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)
       at Microsoft.AspNet.OData.Routing.ODataActionSelector.SelectAction(HttpControllerContext controllerContext)
       at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.SelectAction(HttpRequestMessage request, IHttpRouteData routeData, HttpConfiguration config)
       at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider(HttpRequestMessage request)
       at System.Web.Http.Cors.CorsMessageHandler.<GetCorsPolicyAsync>d__10.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Web.Http.Cors.CorsMessageHandler.<HandleCorsPreflightRequestAsync>d__b.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0.MoveNext()"}}}
    

    In this case, the failure isn't a nullref. Instead, the wrong path is taken through the action selection code, and the result is an InvalidOperationException due to lack of sufficient information to disambiguate the two candidate actions (Get and DoSomething). As @LianwMS observed, this is because of the order of operations in AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider. This method first copies all properties from the current HttpRequestMessage to a new targetRequest, then calls GetRouteData on the original request. GetRouteData adds new properties to the current request as a side effect, but not to targetRequest. This causes routing to fail.

    In my opinion this appears to be both a bug in the CORS implementation, and a design flaw in Web API OData:

    • The CORS implementation should copy all properties from the current request to the target request after all potentially side-effecting operations are complete, including GetRouteData.
    • Web API OData routing depends on mutating the state of HttpRequestMessage properties other than RouteData. This appears to violate the intended design of ASP.NET routing.

    Fixing either would fix this problem, but given that the CORS implementation in classic ASP.NET is no longer being maintained, the only place left to fix this is in Web API OData. However, that would be a very expensive breaking change as it would touch potentially all routing-related code. I don't have enough information at this point to know whether fixing this for ASP.NET Core would be similarly expensive.

    Fortunately, I may have stumbled across the beginnings of a potential workaround. Azure Search has been using a combination of Web API OData 5.9.1 and CORS for four years now, and we never ran into this issue because we install a message handler that calls GetRouteData before the CorsMessageHandler is called. This sets up all the necessary OData-related routing state before AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider is called, which means it copies that state to targetRequest. This allows preflight requests to work.

    Unfortunately, this workaround doesn't work with Web API OData 7.0.1. due to a separate issue. Specifically, calling GetRouteData more than once where ODataPathRouteConstraint.Match succeeds causes HttpRequestMessageExtensions.CreateRequestContainer to throw an exception. If we can fix that issue however, then calling GetRouteData early will continue to be a viable workaround for this CORS issue with classic ASP.NET.

  11. marabooy commented on Oct 1, 2020

    @marabooy
    Member

    Closing this as a it is fixed now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions