Skip to content

Fix: incorrect resource type comparison #821

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

Merged
merged 7 commits into from
Sep 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ public void ConfigureMvc()
{
options.EnableEndpointRouting = true;
options.Filters.AddService<IAsyncJsonApiExceptionFilter>();
options.Filters.AddService<IAsyncResourceTypeMatchFilter>();
options.Filters.AddService<IAsyncQueryStringActionFilter>();
options.Filters.AddService<IAsyncConvertEmptyActionResultFilter>();
ConfigureMvcOptions?.Invoke(options);
Expand Down Expand Up @@ -159,7 +158,6 @@ private void AddMiddlewareLayer()
_services.AddSingleton<IJsonApiApplicationBuilder>(this);
_services.TryAddSingleton<IExceptionHandler, ExceptionHandler>();
_services.TryAddScoped<IAsyncJsonApiExceptionFilter, AsyncJsonApiExceptionFilter>();
_services.TryAddScoped<IAsyncResourceTypeMatchFilter, AsyncResourceTypeMatchFilter>();
_services.TryAddScoped<IAsyncQueryStringActionFilter, AsyncQueryStringActionFilter>();
_services.TryAddScoped<IAsyncConvertEmptyActionResultFilter, AsyncConvertEmptyActionResultFilter>();
_services.TryAddSingleton<IJsonApiInputFormatter, JsonApiInputFormatter>();
Expand Down
51 changes: 0 additions & 51 deletions src/JsonApiDotNetCore/Middleware/AsyncResourceTypeMatchFilter.cs

This file was deleted.

This file was deleted.

60 changes: 59 additions & 1 deletion src/JsonApiDotNetCore/Serialization/JsonApiReader.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Linq;
using System.Threading.Tasks;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Errors;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Logging;
Expand All @@ -17,16 +22,19 @@ public class JsonApiReader : IJsonApiReader
{
private readonly IJsonApiDeserializer _deserializer;
private readonly IJsonApiRequest _request;
private readonly IResourceContextProvider _resourceContextProvider;
private readonly TraceLogWriter<JsonApiReader> _traceWriter;

public JsonApiReader(IJsonApiDeserializer deserializer,
IJsonApiRequest request,
IResourceContextProvider resourceContextProvider,
ILoggerFactory loggerFactory)
{
if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));

_deserializer = deserializer ?? throw new ArgumentNullException(nameof(deserializer));
_request = request ?? throw new ArgumentNullException(nameof(request));
_resourceContextProvider = resourceContextProvider ?? throw new ArgumentNullException(nameof(resourceContextProvider));
_traceWriter = new TraceLogWriter<JsonApiReader>(loggerFactory);
}

Expand Down Expand Up @@ -63,12 +71,40 @@ public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)

ValidatePatchRequestIncludesId(context, model, body);

ValidateIncomingResourceType(context, model);

return await InputFormatterResult.SuccessAsync(model);
}

private void ValidateIncomingResourceType(InputFormatterContext context, object model)
{
if (context.HttpContext.IsJsonApiRequest() && IsPatchOrPostRequest(context.HttpContext.Request))
{
var endpointResourceType = GetEndpointResourceType();
if (endpointResourceType == null)
{
return;
}

var bodyResourceTypes = GetBodyResourceTypes(model);
foreach (var bodyResourceType in bodyResourceTypes)
{
if (bodyResourceType != endpointResourceType)
{
var resourceFromEndpoint = _resourceContextProvider.GetResourceContext(endpointResourceType);
var resourceFromBody = _resourceContextProvider.GetResourceContext(bodyResourceType);

throw new ResourceTypeMismatchException(new HttpMethod(context.HttpContext.Request.Method),
context.HttpContext.Request.Path,
resourceFromEndpoint, resourceFromBody);
}
}
}
}

private void ValidatePatchRequestIncludesId(InputFormatterContext context, object model, string body)
{
if (context.HttpContext.Request.Method == "PATCH")
if (context.HttpContext.Request.Method == HttpMethods.Patch)
{
bool hasMissingId = model is IList list ? HasMissingId(list) : HasMissingId(model);
if (hasMissingId)
Expand Down Expand Up @@ -134,5 +170,27 @@ private async Task<string> GetRequestBody(Stream body)
// https://github.com/aspnet/AspNetCore/issues/7644
return await reader.ReadToEndAsync();
}

private bool IsPatchOrPostRequest(HttpRequest request)
{
return request.Method == HttpMethods.Patch || request.Method == HttpMethods.Post;
}

private IEnumerable<Type> GetBodyResourceTypes(object model)
{
if (model is IEnumerable<IIdentifiable> resourceCollection)
{
return resourceCollection.Select(r => r.GetType()).Distinct();
}

return model == null ? new Type[0] : new[] { model.GetType() };
}

private Type GetEndpointResourceType()
{
return _request.Kind == EndpointKind.Primary
? _request.PrimaryResource.ResourceType
: _request.SecondaryResource?.ResourceType;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -274,31 +274,6 @@ public async Task CreateResource_SimpleResource_HeaderLocationsAreCorrect()
Assert.Equal($"/api/v1/todoItems/{responseItem.Id}", response.Headers.Location.ToString());
}

[Fact]
public async Task CreateResource_ResourceTypeMismatch_IsConflict()
{
// Arrange
string content = JsonConvert.SerializeObject(new
{
data = new
{
type = "people"
}
});

// Act
var (body, response) = await Post("/api/v1/todoItems", content);

// Assert
AssertEqualStatusCode(HttpStatusCode.Conflict, response);

var errorDocument = JsonConvert.DeserializeObject<ErrorDocument>(body);
Assert.Single(errorDocument.Errors);
Assert.Equal(HttpStatusCode.Conflict, errorDocument.Errors[0].StatusCode);
Assert.Equal("Resource type mismatch between request body and endpoint URL.", errorDocument.Errors[0].Title);
Assert.Equal("Expected resource of type 'todoItems' in POST request body at endpoint '/api/v1/todoItems', instead of 'people'.", errorDocument.Errors[0].Detail);
}

[Fact]
public async Task CreateResource_UnknownResourceType_Fails()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System.Net;
using System.Threading.Tasks;
using JsonApiDotNetCore.Serialization.Objects;
using Newtonsoft.Json;
using Xunit;

namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec
{
public sealed class ResourceTypeMismatchTests : FunctionalTestCollection<StandardApplicationFactory>
{
public ResourceTypeMismatchTests(StandardApplicationFactory factory) : base(factory) { }

[Fact]
public async Task Posting_Resource_With_Mismatching_Resource_Type_Returns_Conflict()
{
// Arrange
string content = JsonConvert.SerializeObject(new
{
data = new
{
type = "people"
}
});

// Act
var (body, _) = await Post("/api/v1/todoItems", content);

// Assert
var errorDocument = JsonConvert.DeserializeObject<ErrorDocument>(body);
Assert.Single(errorDocument.Errors);
Assert.Equal(HttpStatusCode.Conflict, errorDocument.Errors[0].StatusCode);
Assert.Equal("Resource type mismatch between request body and endpoint URL.", errorDocument.Errors[0].Title);
Assert.Equal("Expected resource of type 'todoItems' in POST request body at endpoint '/api/v1/todoItems', instead of 'people'.", errorDocument.Errors[0].Detail);
}

[Fact]
public async Task Patching_Resource_With_Mismatching_Resource_Type_Returns_Conflict()
{
// Arrange
string content = JsonConvert.SerializeObject(new
{
data = new
{
type = "people",
id = 1
}
});

// Act
var (body, _) = await Patch("/api/v1/todoItems/1", content);

// Assert
var errorDocument = JsonConvert.DeserializeObject<ErrorDocument>(body);
Assert.Single(errorDocument.Errors);
Assert.Equal(HttpStatusCode.Conflict, errorDocument.Errors[0].StatusCode);
Assert.Equal("Resource type mismatch between request body and endpoint URL.", errorDocument.Errors[0].Title);
Assert.Equal("Expected resource of type 'todoItems' in PATCH request body at endpoint '/api/v1/todoItems/1', instead of 'people'.", errorDocument.Errors[0].Detail);
}

[Fact]
public async Task Patching_Through_Relationship_Link_With_Mismatching_Resource_Type_Returns_Conflict()
{
// Arrange
string content = JsonConvert.SerializeObject(new
{
data = new
{
type = "todoItems",
id = 1
}
});

// Act
var (body, _) = await Patch("/api/v1/todoItems/1/relationships/owner", content);

// Assert
var errorDocument = JsonConvert.DeserializeObject<ErrorDocument>(body);
Assert.Single(errorDocument.Errors);
Assert.Equal(HttpStatusCode.Conflict, errorDocument.Errors[0].StatusCode);
Assert.Equal("Resource type mismatch between request body and endpoint URL.", errorDocument.Errors[0].Title);
Assert.Equal("Expected resource of type 'people' in PATCH request body at endpoint '/api/v1/todoItems/1/relationships/owner', instead of 'todoItems'.", errorDocument.Errors[0].Detail);
}

[Fact]
public async Task Patching_Through_Relationship_Link_With_Multiple_Resources_Types_Returns_Conflict()
{
// Arrange
string content = JsonConvert.SerializeObject(new
{
data = new object[]
{
new { type = "todoItems", id = 1 },
new { type = "articles", id = 2 },
}
});

// Act
var (body, _) = await Patch("/api/v1/todoItems/1/relationships/childrenTodos", content);

// Assert
var errorDocument = JsonConvert.DeserializeObject<ErrorDocument>(body);
Assert.Single(errorDocument.Errors);
Assert.Equal(HttpStatusCode.Conflict, errorDocument.Errors[0].StatusCode);
Assert.Equal("Resource type mismatch between request body and endpoint URL.", errorDocument.Errors[0].Title);
Assert.Equal("Expected resource of type 'todoItems' in PATCH request body at endpoint '/api/v1/todoItems/1/relationships/childrenTodos', instead of 'articles'.", errorDocument.Errors[0].Detail);
}
}
}