nitrogen / simple_bridge

A simple, standardized interface library to Erlang HTTP Servers.
MIT License
112 stars 76 forks source link

Cowboy: Add fake host header when request missing one #79

Closed dmsnell closed 1 year ago

dmsnell commented 1 year ago

@choptastic I'll come back and add more of a description later. I wrote a large summary twice before I realized my commits were failing because my GPG had expired.

Basically this merges in the host value that Cowboy knows when the HTTP header is missing, as it apparently is when running in cowboy:start_tls/3 mode. I suspect this is related to TLS/SNI.

As I think about this I think a better approach might be to add a new host(req()) -> string(). callback to simple_bridge and then call sbw:host(?BRIDGE) inside of wf_context.erl inside of url/0. The Host header is never guaranteed to appear, and if that's the case we might be able to get it from the web server directly, as we can with cowboy, or we might be able to fallback to some reasonable value.

diff --git a/src/lib/wf_context.erl b/src/lib/wf_context.erl
index 656df25..42fe2bc 100644
--- a/src/lib/wf_context.erl
+++ b/src/lib/wf_context.erl
@@ -149,9 +149,12 @@ protocol() ->
 uri() ->
     sbw:uri(?BRIDGE).

+host() ->
+    sbw:host(?BRIDGE).
+
 url() ->
     Protocol = wf:to_list(protocol()),
-    Host = header(host),
+    Host = host(),
     Uri = uri(),
     Protocol ++ "://" ++ Host ++ Uri.

I'll try and think of a better patch later, but this one for now resolves the issue that I found where nitrogen was crashing when calling wf:url() on a cowboy TLS server.