-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Closed
Copy link
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Text.Jsonpartner-impactThis issue impacts a partner who needs to be kept updatedThis issue impacts a partner who needs to be kept updated
Milestone
Description
Background
JsonSerializer today tolerates JSON payloads that contain duplicate properties, following a last-write-wins strategy when binding property values. Duplicate properties can be problematic from a security standpoint since they introduce ambiguity, which can be exploited in the context of JSON interoperability vulnerabilities. We should expose an option that prevents duplicate properties from being accepted.
API Proposal
namespace System.Text.Json.Serialization;
public enum JsonDuplicatePropertyHandling
{
LastWriteWins = 0, // the current default
FirstWriteWins = 1,
Error = 2
}
namespace System.Text.Json;
public partial class JsonSerializerOptions
{
public JsonDuplicatePropertyHandling DuplicatePropertyHandling { get; set; } = JsonDuplicatePropertyHandling.LastWriteWins;
}
public partial class JsonSourceGenerationsOptionsAttribute
{
public JsonDuplicatePropertyHandling DuplicatePropertyHandling { get; set; } = JsonDuplicatePropertyHandling.LastWriteWins;
}API Usage
string json = """{ "Value": 1, "Value": -1 }""";
JsonSerializer.Deserialize<MyPoco>(json).Value; // -1
JsonSerializerOptions options = new () { DuplicatePropertyHandling = JsonDuplicatePropertyHandling.FirstWriteWins }
JsonSerializer.Deserialize<MyPoco>(json).Value; // 1
JsonSerializerOptions options = new () { DuplicatePropertyHandling = JsonDuplicatePropertyHandling.Error }
JsonSerializer.Deserialize<MyPoco>(json).Value; // JsonException
record MyPoco(int Value);Additional Notes
The option should extend to JsonObject but is not applicable to JsonDocument which stores the full JSON payload. We might still be able to enforce lack of duplication which could be expressed as a boolean property on JsonDocumentOptions:
namespace System.Text.Json;
public partial struct JsonDocumentOptions
{
public bool AllowDuplicateProperties { get; set; } = true;
}samsosa
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Text.Jsonpartner-impactThis issue impacts a partner who needs to be kept updatedThis issue impacts a partner who needs to be kept updated