Skip to content

Commit c3e5dbb

Browse files
committed
feat response: add pp_with; have pp hide set-cookie headers
we don't want to accidentally log cookies, they might contain credentials or secret tokens.
1 parent e341f48 commit c3e5dbb

File tree

2 files changed

+43
-7
lines changed

2 files changed

+43
-7
lines changed

src/core/response.ml

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,15 +68,32 @@ exception Bad_req = Bad_req
6868
let fail_raise ~code fmt =
6969
Printf.ksprintf (fun msg -> raise (Bad_req (code, msg))) fmt
7070

71-
let pp out self : unit =
72-
let pp_body out = function
73-
| `String s -> Format.fprintf out "%S" s
74-
| `Stream _ -> Format.pp_print_string out "<stream>"
75-
| `Writer _ -> Format.pp_print_string out "<writer>"
76-
| `Void -> ()
71+
let default_pp_body_ out = function
72+
| `String s -> Format.fprintf out "%S" s
73+
| `Stream _ -> Format.pp_print_string out "<stream>"
74+
| `Writer _ -> Format.pp_print_string out "<writer>"
75+
| `Void -> ()
76+
77+
let pp_with ?(mask_header = fun _ -> false)
78+
?(headers_to_mask = [ "set-cookie" ]) ?(pp_body = default_pp_body_) () out
79+
self : unit =
80+
let headers_to_mask = List.rev_map String.lowercase_ascii headers_to_mask in
81+
(* hide some headers *)
82+
let headers =
83+
List.map
84+
(fun (k, v) ->
85+
let hidden = List.mem k headers_to_mask || mask_header k in
86+
if hidden then
87+
k, "<hidden>"
88+
else
89+
k, v)
90+
self.headers
7791
in
92+
7893
Format.fprintf out "{@[code=%d;@ headers=[@[%a@]];@ body=%a@]}" self.code
79-
Headers.pp self.headers pp_body self.body
94+
Headers.pp headers pp_body self.body
95+
96+
let[@inline] pp out self : unit = pp_with out self
8097
8198
let output_ ~bytes (oc : IO.Output.t) (self : t) : unit =
8299
(* double indirection:

src/core/response.mli

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,25 @@ val fail_raise : code:int -> ('a, unit, string, 'b) format4 -> 'a
109109
@raise Bad_req always
110110
*)
111111

112+
val pp_with :
113+
?mask_header:(string -> bool) ->
114+
?headers_to_mask:string list ->
115+
?pp_body:(Format.formatter -> body -> unit) ->
116+
unit ->
117+
Format.formatter ->
118+
t ->
119+
unit
120+
(** Pretty print the response. The exact format of this printing
121+
is not specified.
122+
@param mask_header function which is given each header name. If it
123+
returns [true], the header's value is masked. The presence of
124+
the header is still printed. Default [fun _ -> false].
125+
@param headers_to_mask a list of headers masked by default.
126+
Default is ["set-cookie"].
127+
@param pp_body body printer
128+
(default fully prints String bodies, but omits stream bodies)
129+
@since NEXT_RELEASE *)
130+
112131
val pp : Format.formatter -> t -> unit
113132
(** Pretty print the response. The exact format is not specified. *)
114133

0 commit comments

Comments
 (0)