diff --git a/docs/areas/docker-instances.md b/docs/areas/docker-instances.md index 617c543a..3d62c9e6 100644 --- a/docs/areas/docker-instances.md +++ b/docs/areas/docker-instances.md @@ -93,6 +93,7 @@ on the snapshots and samples it produces. - Discovery lists **all** containers of an instance, including stopped ones. A container without an ID, with an empty or blank ID, or with an ID longer than 200 characters, and an item of the list that is not a JSON object, is left out. + A container list whose root is not a JSON array fails discovery with `invalid response`, and no image is inspected. - Per container it records: the container ID; the name (the first listed name that is a string, without its leading `/`, or the container ID when it has none); the image reference as the Engine reports it; the local image ID; the compose project (`com.docker.compose.project` label), the stack name (`com.docker.stack.namespace`) and the swarm service @@ -121,7 +122,7 @@ on the snapshots and samples it produces. control characters replaced by spaces ([Integration failures](integration-failures.md#remote-text-fields)). The creation time of a history entry is the Engine's Unix time in seconds, read as UTC; `0`, a negative, an out-of-range or an unreadable value is unknown. A history entry that is not a JSON object is left out and the other entries are - still read. + still read. A history whose root is not a JSON array answers *failed* with `invalid response`. An item of the repo tags, repo digests, environment variables, root file-system layers or of a history entry's tags that is not a JSON string (a number, `true`/`false`, `null`, an object, an array) is left out and the other items are still read ([0071](../decisions/0071-a-docker-engine-string-list-item-that-is-not-a-json-string-is-left-out.md)). @@ -227,7 +228,8 @@ on the snapshots and samples it produces. shown in the UI. - A message or log entry that names an endpoint shows its URL with the user info replaced by `***`; connecting still uses the configured URL. -- A resource collection fails for an instance when the list request fails or times out, or when stats were requested +- A resource collection fails for an instance when the list request fails or times out, when the list's root is not a JSON + array (`invalid response`, no stats request), or when stats were requested and no container could be sampled (`Docker container resource sampling failed for '': no container stats could be read`); it records **no** samples for that instance in that round and logs the failure once as warning 2103, besides warning 3107 for a list request that broke and warning 3111 for each container left out; other instances are not @@ -257,6 +259,8 @@ on the snapshots and samples it produces. Docker Engine container without an ID. - [0074](../decisions/0074-a-docker-engine-stats-or-image-inspect-answer-that-is-not-a-json-object-is-an-invalid-response.md): a Docker Engine stats or image inspect answer that is not a JSON object is an invalid response. +- [0075](../decisions/0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md): + a Docker Engine container list or image history that is not a JSON array is an invalid response. ## Not here diff --git a/docs/areas/integration-failures.md b/docs/areas/integration-failures.md index cbcfbfe2..3f9b3258 100644 --- a/docs/areas/integration-failures.md +++ b/docs/areas/integration-failures.md @@ -31,7 +31,7 @@ operator's logs rely on it; each integration area states only what it adds. failed` (transport failures and responses that break off), `invalid response` or `unexpected error`. The error itself is logged with the failure (a JSON parse failure with a fixed message, [Telemetry](telemetry.md#credentials-and-external-data)). - `invalid response` covers malformed JSON and a JSON string that does not decode as Unicode text, such as a lone - surrogate escape like `\ud800` or bytes that are not UTF-8, a registry answer, or a Docker Engine stats or image inspect answer, whose root is not a JSON object, and a Docker Hub access token whose payload segment is not + surrogate escape like `\ud800` or bytes that are not UTF-8, a registry answer, or a Docker Engine stats or image inspect answer, whose root is not a JSON object, a Docker Engine container list or image history whose root is not a JSON array, and a Docker Hub access token whose payload segment is not base64url. The Docker Hub, OCI and Docker Engine clients refuse the whole body for one in any string value or property name; the Portainer client and the vulnerability providers for one in a field they read; the release feeds report it as `unexpected error`. diff --git a/docs/areas/telemetry.md b/docs/areas/telemetry.md index d42a687a..8aa05a6e 100644 --- a/docs/areas/telemetry.md +++ b/docs/areas/telemetry.md @@ -122,7 +122,7 @@ Every exported signal carries the same resource: - A JSON parse failure of a remote answer, a token payload, the .NET release index or Trivy's report is logged with a fixed message, never the parser's: `Remote JSON is not valid at line , byte (counted from 0)`, with the parser's line and byte position in invariant digits, or `Remote JSON is not valid` when the position is unknown. The - exception has no path and no inner exception, so it carries no remote text; the refusal of a string that does not decode ([Integration failures](integration-failures.md#fixed-failure-reasons)) keeps its own fixed message and its decoding error, which carries no remote text either; the refusal of a registry answer, or of a Docker Engine stats or image inspect answer, whose root is not a JSON object carries the fixed message `The remote response is not a JSON object` and no inner exception. Every parse of external JSON goes through + exception has no path and no inner exception, so it carries no remote text; the refusal of a string that does not decode ([Integration failures](integration-failures.md#fixed-failure-reasons)) keeps its own fixed message and its decoding error, which carries no remote text either; the refusal of a registry answer, or of a Docker Engine stats or image inspect answer, whose root is not a JSON object carries the fixed message `The remote response is not a JSON object` and no inner exception; the refusal of a Docker Engine container list or image history whose root is not a JSON array carries `The remote response is not a JSON array` and no inner exception. Every parse of external JSON goes through `Infrastructure\ExternalJson`. A `Content-Type` charset that cannot be used is refused with the fixed message `The character set of the remote response is not valid` and no inner exception. Decision: [0045](../decisions/0045-json-parse-failures-of-external-data-carry-a-fixed-message-with-their-position.md). diff --git a/docs/decisions/0069-a-docker-engine-list-item-that-is-not-a-json-object-is-left-out.md b/docs/decisions/0069-a-docker-engine-list-item-that-is-not-a-json-object-is-left-out.md index df7c977f..ad4ce7c0 100644 --- a/docs/decisions/0069-a-docker-engine-list-item-that-is-not-a-json-object-is-left-out.md +++ b/docs/decisions/0069-a-docker-engine-list-item-that-is-not-a-json-object-is-left-out.md @@ -42,7 +42,8 @@ still read. The rules are in [Docker instances](../areas/docker-instances.md). samples no container and succeeds with count 0, and a history succeeds without entries, after which derived runtime findings that rested on history text can be deactivated instead of kept. An Engine able to send such items can send an empty list to the same effect today. -- A root that is not a JSON array keeps failing the call. An item of an unexpected kind inside an entry's string list +- A root that is not a JSON array keeps failing the call, with `invalid response` by + [0075](0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md). An item of an unexpected kind inside an entry's string list (a number among a history entry's tags, say) is decided by [0071](0071-a-docker-engine-string-list-item-that-is-not-a-json-string-is-left-out.md). - Revisit, with a warning per left-out item, if operators need to find an Engine that sends such items. diff --git a/docs/decisions/0074-a-docker-engine-stats-or-image-inspect-answer-that-is-not-a-json-object-is-an-invalid-response.md b/docs/decisions/0074-a-docker-engine-stats-or-image-inspect-answer-that-is-not-a-json-object-is-an-invalid-response.md index fcda54e5..4dd251d1 100644 --- a/docs/decisions/0074-a-docker-engine-stats-or-image-inspect-answer-that-is-not-a-json-object-is-an-invalid-response.md +++ b/docs/decisions/0074-a-docker-engine-stats-or-image-inspect-answer-that-is-not-a-json-object-is-an-invalid-response.md @@ -33,7 +33,8 @@ The planning of #581 found the difference. 3. **Refuse a non-object host info answer too** — 0068 rejected it (its option 4): the collector takes a failed and a zero host memory alike as 0, so only a log entry would change. 4. **Refuse a container list or image history root that is not an array in the same change** — the same kind of - defect, but a new parse rule for arrays beyond what the issue asks; proposed as a follow-up issue. + defect, but a new parse rule for arrays beyond what the issue asks; decided by + [0075](0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md). 5. **Map the reader's `InvalidOperationException` to `invalid response`** — rejected by 0019 and 0029 for the misuse the runtime reports with the same type. @@ -48,5 +49,5 @@ in [Docker instances](../areas/docker-instances.md) and - Warnings 3111 and 3112 and the failed inspect result read `invalid response` for such a body instead of `unexpected error`; which container or image is affected, and how, does not change. -- A container list or image history whose root is not an array still reads `unexpected error` until the follow-up - issue decides it. \ No newline at end of file +- A container list or image history whose root is not an array reads `invalid response` by + [0075](0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md). \ No newline at end of file diff --git a/docs/decisions/0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md b/docs/decisions/0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md new file mode 100644 index 00000000..9c26d7cf --- /dev/null +++ b/docs/decisions/0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md @@ -0,0 +1,57 @@ +# 0075: A Docker Engine container list or image history that is not a JSON array is an invalid response + +- **Status:** Accepted +- **Date:** 2026-11-28 +- **Area:** Docker instances +- **Source:** Issue #585 +- **Supersedes:** — + +## Context + +Discovery and resource sampling read the Engine's container list, the image history reads the list of history +entries; each answer is a JSON array, and each item that is not a JSON object is left out +([0069](0069-a-docker-engine-list-item-that-is-not-a-json-object-is-left-out.md)). The client enumerated the root +without checking its kind, so a root of another kind (an object, a string, a number, `true`/`false`, `null`) made the +reader throw `InvalidOperationException`, and the fixed reason +([0009](0009-integration-results-carry-fixed-failure-reasons.md)) of the failed discovery, resource collection or +history was `unexpected error`. Since +[0074](0074-a-docker-engine-stats-or-image-inspect-answer-that-is-not-a-json-object-is-an-invalid-response.md) a stats +or image inspect answer that is not a JSON object reads `invalid response`, so two malformed answers of the same Engine +read differently. Only a broken or hostile Engine, or a proxy in front of it, sends such a body. The planning of #583 +found the difference. + +## Options considered + +1. **Parse the container list and the image history as a JSON array where the body is parsed (chosen)** — the rule of + 0074 and [0073](0073-a-registry-answer-that-is-not-a-json-object-is-an-invalid-response-and-an-entry-that-is-not-one-is-left-out.md) + for the other root kind: the root is refused as malformed JSON is, so the existing handlers answer + `invalid response` without a new handler; the outcome (a failed call) is unchanged. +2. **Keep `unexpected error`** — two reasons for one malformed Engine answer, depending on its root kind, and a reason + that reads like an error of the application. +3. **Read a root that is not an array as an empty list, as 0069 does for an item** — discovery would succeed without + containers, a resource round with no samples and a history without entries, so a malformed answer would read as an + Engine without containers and derived runtime findings resting on history text could be deactivated; an item is left + out because the other items still carry data, a root carries none. +4. **Check the root kind at each of the three call sites** — three copies of one check and its message where the + object check of 0073 sits in one place, so a later call site could miss it. +5. **Map the reader's `InvalidOperationException` to `invalid response`** — rejected by + [0019](0019-remote-json-with-undecodable-strings-is-an-invalid-response.md) and + [0029](0029-registry-calls-answer-every-error-but-the-callers-cancellation-as-failed.md) for the misuse the runtime + reports with the same type. + +## Decision + +Option 1: the Engine's container list, for discovery and for resource sampling, and its image history are parsed as a +JSON array and refused as an invalid response otherwise; the host info keeps the rule of +[0068](0068-an-unreadable-docker-engine-stats-or-host-memory-number-counts-as-missing.md). The reasons are in +[Docker instances](../areas/docker-instances.md) and +[Integration failures](../areas/integration-failures.md#fixed-failure-reasons). + +## Consequences + +- A failed discovery, resource collection or history caused by such a body reads `invalid response` instead of + `unexpected error`, in its result and in a scan run's error message; the calls still fail as before, and warnings + 3104, 3107 and 3109 still name the instance, now with the refusal's fixed message `The remote response is not a JSON + array` as their error. +- Every Engine answer the client reads as an object or an array now refuses the other kinds; only the host info reads + any root. \ No newline at end of file diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 705f616b..f696fdea 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -135,4 +135,5 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [0072](0072-a-registry-string-list-item-that-is-not-a-json-string-is-left-out.md) | A registry string list item that is not a JSON string is left out | Accepted | 2026-11-28 | | [0073](0073-a-registry-answer-that-is-not-a-json-object-is-an-invalid-response-and-an-entry-that-is-not-one-is-left-out.md) | A registry answer that is not a JSON object is an invalid response, and an entry that is not one is left out | Accepted | 2026-11-28 | | [0074](0074-a-docker-engine-stats-or-image-inspect-answer-that-is-not-a-json-object-is-an-invalid-response.md) | A Docker Engine stats or image inspect answer that is not a JSON object is an invalid response | Accepted | 2026-11-28 | +| [0075](0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md) | A Docker Engine container list or image history that is not a JSON array is an invalid response | Accepted | 2026-11-28 | \ No newline at end of file diff --git a/src/DockerUpdateGuard/Docker/DockerInstanceClient.cs b/src/DockerUpdateGuard/Docker/DockerInstanceClient.cs index 4ef7f340..54a3eaa5 100644 --- a/src/DockerUpdateGuard/Docker/DockerInstanceClient.cs +++ b/src/DockerUpdateGuard/Docker/DockerInstanceClient.cs @@ -919,7 +919,7 @@ private static async Task(); @@ -1215,7 +1215,7 @@ public async Task -/// Parses a remote JSON response and refuses a body whose strings do not decode as Unicode text; a parse failure carries no remote text +/// Parses a remote JSON response and refuses a body whose strings do not decode as Unicode text or, where asked, whose root is not of the expected kind; a parse failure carries no remote text /// internal static class RemoteJsonDocument { @@ -19,6 +19,11 @@ internal static class RemoteJsonDocument /// private const string NotAnObjectMessage = "The remote response is not a JSON object"; + /// + /// Message of the exception for a response whose root is not a JSON array + /// + private const string NotAnArrayMessage = "The remote response is not a JSON array"; + #endregion // Constants #region Static methods @@ -53,15 +58,39 @@ public static async Task ParseAsync(Stream stream, CancellationTok /// Stream to parse /// Cancellation token /// Parsed document - public static async Task ParseObjectAsync(Stream stream, CancellationToken cancellationToken) + public static Task ParseObjectAsync(Stream stream, CancellationToken cancellationToken) + { + return ParseRootAsync(stream, JsonValueKind.Object, NotAnObjectMessage, cancellationToken); + } + + /// + /// Parse a stream into a JSON document whose root is an array and verify that every string decodes + /// + /// Stream to parse + /// Cancellation token + /// Parsed document + public static Task ParseArrayAsync(Stream stream, CancellationToken cancellationToken) + { + return ParseRootAsync(stream, JsonValueKind.Array, NotAnArrayMessage, cancellationToken); + } + + /// + /// Parse a stream into a JSON document, verify that every string decodes and that the root is of the expected kind + /// + /// Stream to parse + /// Expected kind of the root + /// Message of the exception for a root of another kind + /// Cancellation token + /// Parsed document + private static async Task ParseRootAsync(Stream stream, JsonValueKind rootKind, string refusalMessage, CancellationToken cancellationToken) { var document = await ParseAsync(stream, cancellationToken).ConfigureAwait(false); - if (document.RootElement.ValueKind != JsonValueKind.Object) + if (document.RootElement.ValueKind != rootKind) { document.Dispose(); - throw new JsonException(NotAnObjectMessage); + throw new JsonException(refusalMessage); } return document; diff --git a/src/Tests/DockerUpdateGuard.Tests/DockerInstanceClientListItemsTests.cs b/src/Tests/DockerUpdateGuard.Tests/DockerInstanceClientListItemsTests.cs index dab6fc7a..b22104d7 100644 --- a/src/Tests/DockerUpdateGuard.Tests/DockerInstanceClientListItemsTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/DockerInstanceClientListItemsTests.cs @@ -1,3 +1,5 @@ +using System.Text.Json; + using DockerUpdateGuard.Configuration; using DockerUpdateGuard.Docker; using DockerUpdateGuard.Infrastructure; @@ -524,7 +526,7 @@ public async Task DockerInstanceClientInspectImageAsyncWhenBodyIsNoObjectReturns } /// - /// Verify an image history answer that is not a JSON array still fails with the fixed unexpected-error reason + /// Verify an image history answer that is not a JSON array fails with the fixed invalid-response reason /// /// JSON of the answer /// Task @@ -533,7 +535,9 @@ public async Task DockerInstanceClientInspectImageAsyncWhenBodyIsNoObjectReturns [DataRow("{}")] [DataRow("\"text\"")] [DataRow("7")] - public async Task DockerInstanceClientGetImageHistoryAsyncWhenBodyIsNoArrayReturnsUnexpectedErrorAsync(string bodyJson) + [DataRow("true")] + [DataRow("null")] + public async Task DockerInstanceClientGetImageHistoryAsyncWhenBodyIsNoArrayReturnsInvalidResponseAsync(string bodyJson) { using var handler = new SequenceHttpMessageHandler(); using var httpClient = CreateHttpClient(handler); @@ -545,7 +549,70 @@ public async Task DockerInstanceClientGetImageHistoryAsyncWhenBodyIsNoArrayRetur var result = await client.GetImageHistoryAsync(CreateInstanceOptions(), "sha256:local-image", TestContext.CancellationToken).ConfigureAwait(false); Assert.AreEqual(ExternalOperationStatus.Failed, result.Status, $"An answer {bodyJson} that is no array must fail the history"); - Assert.AreEqual("Docker image history failed for 'Production': unexpected error", result.Message, "The failure must carry the fixed reason"); + Assert.AreEqual("Docker image history failed for 'Production': invalid response", result.Message, "The failure must carry the fixed reason"); + } + + /// + /// Verify a container list that is not a JSON array fails the discovery with the fixed invalid-response reason, logs it once and sends no further request + /// + /// JSON of the answer + /// Task + [TestMethod] + [TestCategory("AC2")] + [DataRow("{}")] + [DataRow("\"text\"")] + [DataRow("7")] + [DataRow("true")] + [DataRow("null")] + public async Task DockerInstanceClientDiscoverContainersAsyncWhenListBodyIsNoArrayReturnsInvalidResponseAsync(string bodyJson) + { + using var handler = new SequenceHttpMessageHandler(); + using var httpClient = CreateHttpClient(handler); + + handler.AddJsonResponse("https://docker.example.test/v1.41/containers/json?all=1", bodyJson); + + var logger = new TestLogger(); + var client = new DockerInstanceClient(logger, (_, _) => httpClient); + + var result = await client.DiscoverContainersAsync(CreateInstanceOptions(), TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreEqual(ExternalOperationStatus.Failed, result.Status, $"A list {bodyJson} that is no array must fail the discovery"); + Assert.AreEqual("Docker container discovery failed for 'Production': invalid response", result.Message, "The failure must carry the fixed reason"); + + var entry = Assert.ContainsSingle(logger.Entries.Where(logEntry => logEntry.EventId.Id == 3104).ToList(), "The failed discovery must be logged once"); + + Assert.IsInstanceOfType(entry.Exception, "The log entry must carry the JSON exception of the refusal"); + Assert.HasCount(1, handler.Requests, "No request after the list request may be sent"); + } + + /// + /// Verify a container list that is not a JSON array fails the resource collection with the fixed invalid-response reason and sends no stats request + /// + /// JSON of the answer + /// Task + [TestMethod] + [TestCategory("AC3")] + [DataRow("{}")] + [DataRow("\"text\"")] + [DataRow("7")] + [DataRow("true")] + [DataRow("null")] + public async Task DockerInstanceClientCollectContainerResourceUsageAsyncWhenListBodyIsNoArrayReturnsInvalidResponseAsync(string bodyJson) + { + using var handler = new SequenceHttpMessageHandler(); + using var httpClient = CreateHttpClient(handler); + + handler.AddJsonResponse("https://docker.example.test/v1.41/containers/json", bodyJson); + + var client = new DockerInstanceClient(new TestLogger(), (_, _) => httpClient); + + var result = await client.CollectContainerResourceUsageAsync(CreateInstanceOptions(), TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreEqual(ExternalOperationStatus.Failed, result.Status, $"A list {bodyJson} that is no array must fail the sampling"); + Assert.AreEqual("Docker container resource sampling failed for 'Production': invalid response", result.Message, "The failure must carry the fixed reason"); + Assert.DoesNotContain(request => request.RequestUri.Contains("/stats", StringComparison.Ordinal), + handler.Requests, + "No stats request must be sent"); } /// diff --git a/src/Tests/DockerUpdateGuard.Tests/RemoteJsonDocumentTests.cs b/src/Tests/DockerUpdateGuard.Tests/RemoteJsonDocumentTests.cs index 074d957b..4316d1fd 100644 --- a/src/Tests/DockerUpdateGuard.Tests/RemoteJsonDocumentTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/RemoteJsonDocumentTests.cs @@ -201,6 +201,104 @@ public async Task RemoteJsonDocumentParseObjectAsyncWhenAStringDoesNotDecodeThro Assert.IsInstanceOfType(exception.InnerException, $"The refusal of case '{label}' must keep the decoding error as inner exception"); } + /// + /// Verify a body whose root is an array is returned as a parsed document + /// + /// Response body + /// Task + [TestMethod] + [TestCategory("AC1")] + [DataRow("[]")] + [DataRow("[ 1, \"x\", null ]")] + [DataRow("[ {} ]")] + public async Task RemoteJsonDocumentParseArrayAsyncWhenRootIsAnArrayReturnsDocumentAsync(string json) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); + + using var document = await RemoteJsonDocument.ParseArrayAsync(stream, TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreEqual(JsonValueKind.Array, document.RootElement.ValueKind, $"The document of '{json}' must be returned with its root array"); + } + + /// + /// Verify a body whose root is not an array is refused as a JSON exception with the fixed message and no inner exception + /// + /// Response body + /// Task + [TestMethod] + [TestCategory("AC1")] + [DataRow("{}")] + [DataRow("""{ "a": [] }""")] + [DataRow("\"x\"")] + [DataRow("7")] + [DataRow("1.5")] + [DataRow("true")] + [DataRow("false")] + [DataRow("null")] + public async Task RemoteJsonDocumentParseArrayAsyncWhenRootIsNoArrayThrowsJsonExceptionAsync(string json) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); + + var exception = await Assert.ThrowsExactlyAsync(() => RemoteJsonDocument.ParseArrayAsync(stream, TestContext.CancellationToken), + $"The root '{json}' must be refused as a JSON exception") + .ConfigureAwait(false); + + Assert.AreEqual("The remote response is not a JSON array", exception.Message, $"The refusal of '{json}' must carry the fixed message"); + Assert.IsNull(exception.InnerException, $"The refusal of '{json}' must carry no inner exception"); + } + + /// + /// Verify an array body with one string that does not decode is refused by the array parse as by the plain parse + /// + /// Name of the case + /// Response body + /// Whether the case is a JSON escape that must keep its backslash + /// Task + [TestMethod] + [TestCategory("AC1")] + [DynamicData(nameof(GetUndecodableArrayBodies))] + public async Task RemoteJsonDocumentParseArrayAsyncWhenAStringDoesNotDecodeThrowsJsonExceptionAsync(string label, byte[] body, bool isEscape) + { + if (isEscape) + { + Assert.Contains((byte)Backslash, body, $"The input of case '{label}' must still carry the backslash of its escape"); + } + + using var stream = new MemoryStream(body); + + var exception = await Assert.ThrowsExactlyAsync(() => RemoteJsonDocument.ParseArrayAsync(stream, TestContext.CancellationToken), + $"Case '{label}' must be refused as a JSON exception") + .ConfigureAwait(false); + + Assert.IsInstanceOfType(exception.InnerException, $"The refusal of case '{label}' must keep the decoding error as inner exception"); + } + + /// + /// Verify an undecodable string is refused before the root kind is checked, so a body with an object root reads the decoding refusal + /// + /// Name of the case + /// Response body with an object root + /// Whether the case is a JSON escape that must keep its backslash + /// Task + [TestMethod] + [TestCategory("AC1")] + [DynamicData(nameof(GetUndecodableBodies))] + public async Task RemoteJsonDocumentParseArrayAsyncWhenObjectRootHasUndecodableStringThrowsDecodingRefusalAsync(string label, byte[] body, bool isEscape) + { + if (isEscape) + { + Assert.Contains((byte)Backslash, body, $"The input of case '{label}' must still carry the backslash of its escape"); + } + + using var stream = new MemoryStream(body); + + var exception = await Assert.ThrowsExactlyAsync(() => RemoteJsonDocument.ParseArrayAsync(stream, TestContext.CancellationToken), + $"Case '{label}' must be refused as a JSON exception") + .ConfigureAwait(false); + + Assert.IsInstanceOfType(exception.InnerException, $"Case '{label}' must read the decoding refusal, not the root refusal"); + } + #endregion // Methods #region Static methods @@ -235,6 +333,20 @@ public static IEnumerable GetUndecodableBodies() yield return ["raw encoded surrogate", CreateBody([(byte)'{', (byte)'"', (byte)'a', (byte)'"', (byte)':', (byte)'"', 0xED, 0xA0, 0x80, (byte)'"', (byte)'}']), false]; } + /// + /// Bodies with one string that does not decode, each wrapped in an array + /// + /// Rows of case name, body and whether the case is an escape + public static IEnumerable GetUndecodableArrayBodies() + { + foreach (var row in GetUndecodableBodies()) + { + var body = (byte[])row[1]; + + yield return [row[0], CreateBody([(byte)'[', .. body, (byte)']']), row[2]]; + } + } + /// /// Create a body from bytes ///