Skip to content

Commit 1b49eba

Browse files
committed
CA-406403: Do not return HTTP 500 when Accept header can't be parsed
/update_rrds returned a 500 HTTP code in some cases where the accept header was invalid. Now these cases are treated in the same way as a lack of Accept header. Signed-off-by: Pau Ruiz Safont <[email protected]>
1 parent 519a4a0 commit 1b49eba

File tree

2 files changed

+14
-14
lines changed

2 files changed

+14
-14
lines changed

ocaml/libs/http-lib/http.mli

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ module Accept : sig
5555
val equal : t -> t -> bool
5656

5757
val of_string : string -> t list
58+
(** [of_string accept_hdr] Returns a list of weighted media types represented
59+
by [accept_hdr]. If [accept_hdr can't be parsed, raises [Parse_failure]].
60+
*)
5861

5962
val to_string : t -> string
6063

ocaml/xcp-rrdd/bin/rrdd/rrdd_http_handler.ml

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,17 @@ let content_xml = content_hdr_of_mime mime_xml
1818

1919
let client_prefers_json req =
2020
let module Accept = Http.Accept in
21-
match req.Http.Request.accept with
22-
| None ->
23-
List.mem_assoc "json" req.Http.Request.query
24-
| Some accept -> (
25-
let accepted = Accept.of_string accept in
26-
let negotiated = Accept.preferred ~from:[mime_json; mime_xml] accepted in
27-
match negotiated with
28-
| x :: _ when String.equal x mime_json ->
29-
true
30-
| [] ->
31-
List.mem_assoc "json" req.Http.Request.query
32-
| _ ->
33-
false
34-
)
21+
let ( let* ) = Option.bind in
22+
let map_head f lst = List.nth_opt lst 0 |> Option.map f in
23+
let prefers =
24+
let* accept = req.Http.Request.accept in
25+
let* accepted =
26+
try Some (Accept.of_string accept) with Accept.Parse_failure _ -> None
27+
in
28+
let negotiated = Accept.preferred ~from:[mime_json; mime_xml] accepted in
29+
map_head (fun x -> String.equal x mime_json) negotiated
30+
in
31+
Option.value ~default:(List.mem_assoc "json" req.Http.Request.query) prefers
3532

3633
let content_type json = if json then content_json else content_xml
3734

0 commit comments

Comments
 (0)