Typed request bodies refuse enum numbers and digit strings #323

Closed
opened 2026-11-05 19:14:48 -05:00 by claude · 0 comments
Owner

Part of epic #316.

  • Kind: bug
  • Area: api
  • Priority: low (as epic)
  • Milestone: Post-release fixes
  • Agent: coder
  • Depends on: #296
  • Decisions: Q-API-1 (#260)

Why

POST /api/zones stores "type":"99", and POST /api/dhcp-tag-rules stores match mode 5. MVC
reads enums through each type's attribute converter, and both converters accept numbers.

What changes

A new Ninlil.Web/Serialization/RequestEnumNameJsonConverterFactory.cs is registered in
Program.cs AddJsonOptions. It reads declared names only (case-insensitive; comma list for
flags) and writes through the type's own converter, so responses are unchanged. Shared converters
are not touched.

Acceptance

  • dotnet test src/dotnet/tests/Ninlil.Web.Tests --filter "FullyQualifiedName~EnumNamesOnlyRequestBodyTests|FullyQualifiedName~RequestEnumNameJsonConverterTests" passes. The ReturnsBadRequest rows fail before the change.
  • RequestBodies_EveryEnumPropertyType_IsReadByTheNameOnlyConverter passes.
  • OpenApiSnapshotTests passes unchanged (otherwise WP-4).
  • Every item in Before you finish that applies is done.

Source

Architect design for #316: §1.2, §1.3 and WP-1. Program.cs:744, EnumDescriptionJsonConverter.cs:26-28,
DhcpModels.cs:238-246, ZoneModels.cs:85-106.

Work package detail

  • Goal: every typed [FromBody] model refuses digit strings, JSON numbers and undefined
    values for enum fields. Responses are unchanged.

  • Files:

    • src/dotnet/src/Ninlil.Web/Serialization/RequestEnumNameJsonConverterFactory.cs (new): the
      factory and the converter.
    • src/dotnet/src/Ninlil.Web/Program.cs:744: chain
      .AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new RequestEnumNameJsonConverterFactory())).
    • src/dotnet/tests/Ninlil.Web.Tests/RequestEnumNameJsonConverterTests.cs (new, pure unit
      tests; shape like StorageConnectionStringAssemblerTests).
    • src/dotnet/tests/Ninlil.Web.Tests/EnumNamesOnlyRequestBodyTests.cs (new, shared host; shape
      like EnumNamesOnlyApiTests).
    • Any existing Web test that posts a numeric enum value: change it to the name.
  • Interfaces:

    public sealed class RequestEnumNameJsonConverterFactory : JsonConverterFactory
    {
        // True for an enum type whose [JsonConverter] attribute names EnumDescriptionJsonConverter<>
        // or JsonStringEnumConverter / JsonStringEnumConverter<> (or a subclass). Other enums keep
        // their default handling.
        public override bool CanConvert(Type typeToConvert);
        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options);
    }
    
    public sealed class RequestEnumNameJsonConverter<TEnum> : JsonConverter<TEnum>
        where TEnum : struct, Enum
    {
        // writer: the converter built from the type's own [JsonConverter] attribute (for a factory
        // attribute, its CreateConverter(typeof(TEnum), options)).
        public RequestEnumNameJsonConverter(JsonConverter<TEnum> writer);
        public static string ValidNames { get; } // the names Write emits for each defined member, ", "-joined
        public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options);
        public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options); // delegates
    }
    
  • Read rules:

    • The token must be String.
    • The text, trimmed (each comma part, for a [Flags] type), must equal, ignoring case, a
      defined member's name or one of its declared names. Use
      GetEnumDescriptionsTypeExtension.GetEnumDescriptions with the three attribute checks of
      EnumDescriptionJsonConverter.cs:61-66.
    • A non-flags type takes no comma.
    • Anything else throws JsonException("'<text>' is not a valid value for <Type>. Valid values: <ValidNames>.").
    • Nullable T? needs no code: System.Text.Json handles null before the converter.
  • Constraints:

    • Do not change EnumDescriptionJsonConverter, ToEnumStringExtension or any type's
      [JsonConverter] attribute (§1.3).
    • No schema, option or ENVIRONMENT.md change.
    • Comment standard: the factory's summary says why it is MVC-only and names the precedence
      rule.
  • Acceptance (Web.Tests): red first means the ReturnsBadRequest rows fail on today's
    201/200.

    • CreateTagRule_WithADigitStringNumberOrUndefinedMatchMode_ReturnsBadRequest ("1", 1,
      "5", 5, both fields).
    • CreateTagRule_WithEachMatchModeName_IsCreated (Exact, Prefix, prefix).
    • CreateZone_WithADigitStringForAnEnumField_ReturnsBadRequest (type "0"/"99",
      dnssecAlgorithm "13"/"200", denialOfExistenceMode "1"/"99", transferTransport "0").
    • CreateZone_WithAJsonNumberForAnEnumField_ReturnsBadRequest (pins today's 400).
    • CreateZone_WithTheConsoleWireNames_IsCreated (Primary, ECDSAP256SHA256, Nsec3,
      Plain).
    • CreateDnssecKey_WithADigitStringRoleOrAlgorithm_ReturnsBadRequest ("1", "9", "13",
      "200").
    • CreateDnssecKey_WithWireAlgorithmName_IsCreated.
    • CreateRecord_WithADigitStringTypeOrClass_ReturnsBadRequest ("1").
    • CreateClientSchedule_WithADigitStringOrMaskDaysOfWeek_ReturnsBadRequest ("3", 3).
    • CreateClientSchedule_WithACommaListOfDayNames_StoresIt ("Sunday, Monday", read back
      identically).
    • AdminResetPassword_WithADigitStringMode_ReturnsBadRequest.
    • RequestBodies_EveryEnumPropertyType_IsReadByTheNameOnlyConverter: walk the ApiExplorer
      body parameter types recursively, including list elements, and assert CanConvert for each
      enum type. DnsAccessControlCapabilityEnum is reached only as string[], so it does not
      appear.
    • The 400 body names the field and contains the valid names.
  • Acceptance (unit, RequestEnumNameJsonConverterTests):

    • Read_ForADigitString_ThrowsJsonException
    • Read_ForAJsonNumber_ThrowsJsonException
    • Read_ForAMemberNameInAnyCase_ReturnsTheMember
    • Read_ForADeclaredWireName_ReturnsTheMember (RSASHA256, DSA-NSEC3-SHA1)
    • Read_ForAFlagsCommaListOfNames_CombinesThem
    • Read_ForAFlagsListWithADigitPart_ThrowsJsonException
    • Read_ForACommaListOnANonFlagsEnum_ThrowsJsonException
    • Write_ForEveryValueIncludingAnUnnamedCode_MatchesTheAttributeConverter (for example
      (DnsResourceRecordTypeEnum)65280 still writes "65280")
    • CanConvert_ForAnEnumWithoutAStringConverterAttribute_ReturnsFalse
  • Non-goals: merge-patch sites (WP-2), record data (D2), query strings (D3), stored rows
    (D4).

  • Changes: REST API behaviour, yes. The OpenAPI document should be unchanged, because
    Swashbuckle derives enum lists from Write; if OpenApiSnapshotTests fails, WP-4 runs.
    Schema, no. Options, no. README, in WP-5.

  • Gate:

    • dotnet build Ninlil.slnx -p:NinlilSkipAngularBuild=true (0 warnings).
    • dotnet test src/dotnet/tests/Ninlil.Web.Tests.
    • dotnet csharpier check .
Part of epic #316. - **Kind:** bug - **Area:** api - **Priority:** low (as epic) - **Milestone:** Post-release fixes - **Agent:** coder - **Depends on:** #296 - **Decisions:** Q-API-1 (#260) #### Why `POST /api/zones` stores `"type":"99"`, and `POST /api/dhcp-tag-rules` stores match mode `5`. MVC reads enums through each type's attribute converter, and both converters accept numbers. #### What changes A new `Ninlil.Web/Serialization/RequestEnumNameJsonConverterFactory.cs` is registered in `Program.cs` `AddJsonOptions`. It reads declared names only (case-insensitive; comma list for flags) and writes through the type's own converter, so responses are unchanged. Shared converters are not touched. #### Acceptance - [ ] `dotnet test src/dotnet/tests/Ninlil.Web.Tests --filter "FullyQualifiedName~EnumNamesOnlyRequestBodyTests|FullyQualifiedName~RequestEnumNameJsonConverterTests"` passes. The `ReturnsBadRequest` rows fail before the change. - [ ] `RequestBodies_EveryEnumPropertyType_IsReadByTheNameOnlyConverter` passes. - [ ] `OpenApiSnapshotTests` passes unchanged (otherwise WP-4). - [ ] Every item in [Before you finish](https://git.lantea.one/lantea-one/ninlil/src/branch/main/AGENTS.md#before-you-finish) that applies is done. #### Source Architect design for #316: §1.2, §1.3 and WP-1. `Program.cs:744`, `EnumDescriptionJsonConverter.cs:26-28`, `DhcpModels.cs:238-246`, `ZoneModels.cs:85-106`. ### Work package detail - **Goal:** every typed `[FromBody]` model refuses digit strings, JSON numbers and undefined values for enum fields. Responses are unchanged. - **Files:** - `src/dotnet/src/Ninlil.Web/Serialization/RequestEnumNameJsonConverterFactory.cs` (new): the factory and the converter. - `src/dotnet/src/Ninlil.Web/Program.cs:744`: chain `.AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new RequestEnumNameJsonConverterFactory()))`. - `src/dotnet/tests/Ninlil.Web.Tests/RequestEnumNameJsonConverterTests.cs` (new, pure unit tests; shape like `StorageConnectionStringAssemblerTests`). - `src/dotnet/tests/Ninlil.Web.Tests/EnumNamesOnlyRequestBodyTests.cs` (new, shared host; shape like `EnumNamesOnlyApiTests`). - Any existing Web test that posts a numeric enum value: change it to the name. - **Interfaces:** ```csharp public sealed class RequestEnumNameJsonConverterFactory : JsonConverterFactory { // True for an enum type whose [JsonConverter] attribute names EnumDescriptionJsonConverter<> // or JsonStringEnumConverter / JsonStringEnumConverter<> (or a subclass). Other enums keep // their default handling. public override bool CanConvert(Type typeToConvert); public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options); } public sealed class RequestEnumNameJsonConverter<TEnum> : JsonConverter<TEnum> where TEnum : struct, Enum { // writer: the converter built from the type's own [JsonConverter] attribute (for a factory // attribute, its CreateConverter(typeof(TEnum), options)). public RequestEnumNameJsonConverter(JsonConverter<TEnum> writer); public static string ValidNames { get; } // the names Write emits for each defined member, ", "-joined public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options); public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options); // delegates } ``` - **Read rules:** - The token must be `String`. - The text, trimmed (each comma part, for a `[Flags]` type), must equal, ignoring case, a defined member's name or one of its declared names. Use `GetEnumDescriptionsTypeExtension.GetEnumDescriptions` with the three attribute checks of `EnumDescriptionJsonConverter.cs:61-66`. - A non-flags type takes no comma. - Anything else throws `JsonException("'<text>' is not a valid value for <Type>. Valid values: <ValidNames>.")`. - Nullable `T?` needs no code: System.Text.Json handles `null` before the converter. - **Constraints:** - Do not change `EnumDescriptionJsonConverter`, `ToEnumStringExtension` or any type's `[JsonConverter]` attribute (§1.3). - No schema, option or `ENVIRONMENT.md` change. - Comment standard: the factory's summary says why it is MVC-only and names the precedence rule. - **Acceptance (Web.Tests):** red first means the `ReturnsBadRequest` rows fail on today's 201/200. - `CreateTagRule_WithADigitStringNumberOrUndefinedMatchMode_ReturnsBadRequest` (`"1"`, `1`, `"5"`, `5`, both fields). - `CreateTagRule_WithEachMatchModeName_IsCreated` (`Exact`, `Prefix`, `prefix`). - `CreateZone_WithADigitStringForAnEnumField_ReturnsBadRequest` (type `"0"`/`"99"`, dnssecAlgorithm `"13"`/`"200"`, denialOfExistenceMode `"1"`/`"99"`, transferTransport `"0"`). - `CreateZone_WithAJsonNumberForAnEnumField_ReturnsBadRequest` (pins today's 400). - `CreateZone_WithTheConsoleWireNames_IsCreated` (`Primary`, `ECDSAP256SHA256`, `Nsec3`, `Plain`). - `CreateDnssecKey_WithADigitStringRoleOrAlgorithm_ReturnsBadRequest` (`"1"`, `"9"`, `"13"`, `"200"`). - `CreateDnssecKey_WithWireAlgorithmName_IsCreated`. - `CreateRecord_WithADigitStringTypeOrClass_ReturnsBadRequest` (`"1"`). - `CreateClientSchedule_WithADigitStringOrMaskDaysOfWeek_ReturnsBadRequest` (`"3"`, `3`). - `CreateClientSchedule_WithACommaListOfDayNames_StoresIt` (`"Sunday, Monday"`, read back identically). - `AdminResetPassword_WithADigitStringMode_ReturnsBadRequest`. - `RequestBodies_EveryEnumPropertyType_IsReadByTheNameOnlyConverter`: walk the ApiExplorer body parameter types recursively, including list elements, and assert `CanConvert` for each enum type. `DnsAccessControlCapabilityEnum` is reached only as `string[]`, so it does not appear. - The 400 body names the field and contains the valid names. - **Acceptance (unit, `RequestEnumNameJsonConverterTests`):** - `Read_ForADigitString_ThrowsJsonException` - `Read_ForAJsonNumber_ThrowsJsonException` - `Read_ForAMemberNameInAnyCase_ReturnsTheMember` - `Read_ForADeclaredWireName_ReturnsTheMember` (`RSASHA256`, `DSA-NSEC3-SHA1`) - `Read_ForAFlagsCommaListOfNames_CombinesThem` - `Read_ForAFlagsListWithADigitPart_ThrowsJsonException` - `Read_ForACommaListOnANonFlagsEnum_ThrowsJsonException` - `Write_ForEveryValueIncludingAnUnnamedCode_MatchesTheAttributeConverter` (for example `(DnsResourceRecordTypeEnum)65280` still writes `"65280"`) - `CanConvert_ForAnEnumWithoutAStringConverterAttribute_ReturnsFalse` - **Non-goals:** merge-patch sites (WP-2), record `data` (D2), query strings (D3), stored rows (D4). - **Changes:** REST API behaviour, yes. The OpenAPI document should be unchanged, because Swashbuckle derives enum lists from `Write`; if `OpenApiSnapshotTests` fails, WP-4 runs. Schema, no. Options, no. README, in WP-5. - **Gate:** - `dotnet build Ninlil.slnx -p:NinlilSkipAngularBuild=true` (0 warnings). - `dotnet test src/dotnet/tests/Ninlil.Web.Tests`. - `dotnet csharpier check .`
Sign in to join this conversation.
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
lantea-one/ninlil#323
No description provided.