Skip to content
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
19 changes: 12 additions & 7 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ Three sections:
`expected.body` is the JSON response body. Compare bodies as JSON values:
member order is not significant.
- `error: "invalid status"` means constructing the error must fail.
- **`parse`**: each case gives a response `input` (`status` and the raw `body`
text) and the `expected` error read from it: `status`, `expose`, `title`,
`detail`, `type` and `instance` when present, and the remaining members as
- **`parse`**: each case gives a response `input` (`status` and exactly one of
`body`, the body as text to send UTF-8 encoded, or `body_hex`, the body's
exact bytes in hexadecimal) and the `expected` error read from it. A runner
builds a response from those bytes and passes it to the package's public
parser. The expected error has `status`, `expose`, `title`, `detail`,
`type` and `instance` when present, and the remaining members as
`extensions`. The error's internal message is not pinned.
- **`defaults`**: for every status from 400 to 599, the `title` and `detail`
an error gets when neither is set and its message is not exposed.
Expand All @@ -47,10 +50,12 @@ The rules the cases pin:
an object, and `false`, `0` and `null` survive inside nested values. A title or
detail of `"0"` is set, not empty.
- `content-type` defaults to `application/problem+json`.
- Parsing ignores a leading UTF-8 byte-order mark. It takes the body's
`status` when it is a JSON number whose value is an integer from 400 to 599
(`404`, `404.0` and `4.04e2` all count), else the response's status, else
500. A member of the wrong JSON type, or `null`, is ignored.
- Parsing decodes the body as strict UTF-8 and ignores one leading UTF-8
byte-order mark. A body that is not valid UTF-8, such as Latin-1 or UTF-16
text, is not a problem (below), even when it would decode to one.
- Parsing takes the body's `status` when it is a JSON number whose value is
an integer from 400 to 599 (`404`, `404.0` and `4.04e2` all count), else the
response's status, else 500. A member of the wrong JSON type, or `null`, is ignored.
- A parsed `detail` is the error's message, not an explicit detail: like any
message, it is public only when the error is exposed, so a 5xx problem's
detail is replaced by the default.
Expand Down
56 changes: 56 additions & 0 deletions conformance/vectors/problem-details.json
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,62 @@
"recordId": "9007199254740993"
}
}
},
{
"name": "utf8",
"input": {
"status": 409,
"body_hex": "7b227469746c65223a22436166c3a9222c22737461747573223a3432327d"
},
"expected": {
"status": 422,
"expose": true,
"title": "Café",
"detail": "The request was well-formed but contained semantic errors.",
"extensions": {}
}
},
{
"name": "utf8-bom",
"input": {
"status": 409,
"body_hex": "efbbbf7b227469746c65223a22436166c3a9222c22737461747573223a3432327d"
},
"expected": {
"status": 422,
"expose": true,
"title": "Café",
"detail": "The request was well-formed but contained semantic errors.",
"extensions": {}
}
},
{
"name": "utf16le-bom",
"input": {
"status": 409,
"body_hex": "fffe7b0022007400690074006c00650022003a002200430061006600e90022002c00220073007400610074007500730022003a003400320032007d00"
},
"expected": {
"status": 409,
"expose": false,
"title": "Conflict",
"detail": "The request conflicts with the current state of the resource.",
"extensions": {}
}
},
{
"name": "latin1-in-title",
"input": {
"status": 409,
"body_hex": "7b227469746c65223a22436166e9222c22737461747573223a3432327d"
},
"expected": {
"status": 409,
"expose": false,
"title": "Conflict",
"detail": "The request conflicts with the current state of the resource.",
"extensions": {}
}
}
],
"defaults": [
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/udibo-http-error/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ impl HttpError {
/// - `title`, `type` and `instance` are kept when they are non-empty
/// strings; a member of the wrong JSON type, or `null`, is ignored. Every
/// other member becomes an extension.
/// - The body is read as strict UTF-8 after one optional leading
/// byte-order mark. A body in another encoding, such as Latin-1 or
/// UTF-16, is not a problem.
/// - A body that is not a JSON object with a non-null `status`, `title` or
/// `type` gives an unexposed error with the default title and detail.
///
Expand Down
18 changes: 16 additions & 2 deletions rust/crates/udibo-http-error/tests/conformance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,21 @@ fn headers_json(headers: &HeaderMap) -> Value {
Value::Object(map)
}

fn body_bytes(input: &Value) -> Vec<u8> {
match (input.get("body"), input.get("body_hex")) {
(Some(body), None) => body.as_str().unwrap().as_bytes().to_vec(),
(None, Some(hex)) => {
let hex = hex.as_str().unwrap();
assert_eq!(hex.len() % 2, 0, "body_hex has an odd length");
(0..hex.len())
.step_by(2)
.map(|index| u8::from_str_radix(&hex[index..index + 2], 16).unwrap())
.collect()
}
_ => panic!("a parse input has exactly one of body and body_hex"),
}
}

#[test]
fn serialize() {
let cases = section("serialize");
Expand Down Expand Up @@ -135,8 +150,7 @@ fn parse() {
let name = case["name"].as_str().unwrap();
let input = &case["input"];
let status = u16::try_from(input["status"].as_u64().unwrap()).unwrap();
let error =
HttpError::from_problem_body(status, input["body"].as_str().unwrap().as_bytes());
let error = HttpError::from_problem_body(status, &body_bytes(input));
let expected = &case["expected"];
assert_eq!(
json!(error.status().as_u16()),
Expand Down
18 changes: 18 additions & 0 deletions rust/crates/udibo-http-error/tests/http_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,21 @@ fn ignores_a_status_too_large_for_a_status_code() {
let error = HttpError::from_problem_body(404, br#"{"status": -404, "title": "x"}"#);
assert_eq!(error.status().as_u16(), 404);
}

#[test]
fn reads_a_body_that_is_not_utf8_as_not_a_problem() {
let latin1 = b"{\"title\":\"Caf\xe9\",\"status\":422}";
let error = HttpError::from_problem_body(409, latin1);
assert_eq!(error.status().as_u16(), 409);
assert!(!error.expose());
assert_eq!(error.title(), "Conflict");
assert!(error.extensions().is_empty());
}

#[test]
fn ignores_only_one_byte_order_mark() {
let body = b"\xEF\xBB\xBF\xEF\xBB\xBF{\"title\":\"x\",\"status\":422}";
let error = HttpError::from_problem_body(409, body);
assert_eq!(error.status().as_u16(), 409);
assert!(!error.expose());
}
12 changes: 9 additions & 3 deletions typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@ language-neutral vectors in
[`conformance/vectors/problem-details.json`](../conformance/vectors/problem-details.json),
which every language's package passes.

Extension values keep their JSON type. Integers from -9007199254740991 through
9007199254740991 are exchanged exactly with every other http-error package.
JavaScript reads JSON numbers as 64-bit floats, so send a larger ID or counter
as a decimal string.

#### `detail`

`detail` is the message the client sees, so it is always safe to render. It
Expand Down Expand Up @@ -188,9 +193,10 @@ Converts anything caught into an `HttpError`:
- A Problem Details object becomes the error it describes. Its `detail`
becomes the message, so a 5xx problem's detail stays private unless you
expose it.
- A `Response` is parsed as Problem Details and returns a `Promise`. A body
that is not Problem Details gives an unexposed error with the response's
status (500 when that is not an error status).
- A `Response` is parsed as Problem Details and returns a `Promise`. Its body
is decoded as strict UTF-8, allowing one leading byte-order mark. A body that
is not valid UTF-8, or not Problem Details, gives an unexposed error with the
response's status (500 when that is not an error status).
- Anything else becomes a 500 whose `cause` is that value.

```ts
Expand Down
12 changes: 10 additions & 2 deletions typescript/src/conformance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ interface SerializeCase {

interface ParseCase {
name: string;
input: { status: number; body: string };
input: { status: number } & ({ body: string } | { body_hex: string });
expected: {
status: number;
expose: boolean;
Expand Down Expand Up @@ -92,10 +92,18 @@ describe("problem-details vectors: serialize", () => {
);
});

function responseBody(
input: ParseCase["input"],
): string | Uint8Array<ArrayBuffer> {
return "body" in input
? input.body
: new Uint8Array(Buffer.from(input.body_hex, "hex"));
}

describe("problem-details vectors: parse", () => {
it.each(vectors.parse)("$name", async ({ input, expected }) => {
const error = await HttpError.from(
new Response(input.body, { status: input.status }),
new Response(responseBody(input), { status: input.status }),
);
expect({
status: error.status,
Expand Down
23 changes: 23 additions & 0 deletions typescript/src/mod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,29 @@ describe("HttpError.from", () => {
expect(error.message).toBe("could not parse problem details response");
expect(error.cause).toBeInstanceOf(SyntaxError);
});

it("keeps the decoding failure of a body that is not UTF-8 as the cause", async () => {
const latin1 = new Uint8Array(
Buffer.from('{"title":"Caf\xe9","status":422}', "latin1"),
);
const error = await HttpError.from(new Response(latin1, { status: 409 }));
expect([error.status, error.expose, error.title]).toEqual([
409,
false,
"Conflict",
]);
expect(error.message).toBe("could not parse problem details response");
expect(error.cause).toBeInstanceOf(TypeError);
});

it("ignores only one leading byte-order mark", async () => {
const error = await HttpError.from(
new Response('\uFEFF\uFEFF{"title":"x","status":422}', {
status: 409,
}),
);
expect([error.status, error.expose]).toEqual([409, false]);
});
});

describe("isHttpErrorLike", () => {
Expand Down
13 changes: 9 additions & 4 deletions typescript/src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,10 @@ export class HttpError<
* - Any other `Error` becomes a 500 whose cause is that error.
* - A Problem Details object becomes the error it describes; its `detail`
* becomes the message, which is public only when the error is exposed.
* - A `Response` is parsed as Problem Details, asynchronously. A body that
* is not Problem Details gives an unexposed error with the response's
* status (500 when that is not an error status).
* - A `Response` is parsed as Problem Details, asynchronously. Its body is
* decoded as strict UTF-8, allowing one leading byte-order mark. A body
* that is not valid UTF-8 or not Problem Details gives an unexposed error
* with the response's status (500 when that is not an error status).
* - Anything else becomes a 500 whose cause is that value.
*/
static from<Extensions extends object = Record<string, unknown>>(
Expand Down Expand Up @@ -332,7 +333,11 @@ export class HttpError<
});
let body: unknown;
try {
body = await response.json();
body = JSON.parse(
new TextDecoder("utf-8", { fatal: true }).decode(
await response.arrayBuffer(),
),
);
} catch (parseError) {
return unparsed("could not parse problem details response", parseError);
}
Expand Down
Loading