WebSocket connection to Haven fails on "Upgrade: websocket" header (NGINX on NixOS)
Deploying Haven locally, either via the NixOS module or by compiling it from the repo head, configured to listen on port 21498, shows the "homepage" correctly when connecting locally via browser (http://127.0.0.1:21498/) or via curl, no errors from logs/stdout. However, using NGINX as a proxy, configured according to the instructions in the repo documentation, returns a 400 Bad Request. Testing via curl, mimicking NGINX incoming traffic, the problem appears to be:
curl -v --http1.1 -H "Host: nostr.domain.tld" \
-H "Upgrade: websocket" \ # <= this header cause the 400 error
-H "Connection: Upgrade" \
http://127.0.0.1:21498
BTW the exact same NGINX vhost setup serves Strfry correctly, so I'd rule out an issue with NGINX or NixOS in particular, but I don't know what else to try in terms of debugging...
(Not much) relevant vhost setup
virtualHosts."nostr.domain.tld" = {
enableACME = true;
forceSSL = true;
default = true;
locations."/" = {
proxyPass = "http://127.0.0.1:21498";
proxyWebsockets = true;
extraConfig = ''
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_buffering off; # no change if suppressed
proxy_read_timeout 3600s; # equally as above
''; # extraConfig
}; # locations."/"
}; # virtualHosts."nostr.domain.tld"
Globally for NGINX clientMaxBodySize = "150m"; and proxy_http_version is 1.1 but given the curl test seems to be not much relevant anyway...
I’m not sure anyone here will be able to help much with NixOS NGINX module configuration troubleshooting. You might have better luck asking in NixOS and NGINX specific communities, where people are more familiar with it.
Haven will, of course, play ball with NGINX and any other reverse proxies, as long as they forward the expected headers as described in the documentation.
One thing you can do is compare the output of nginx -T on your box with what is in the docs, or the output of docker compose exec nginx-proxy nginx -T from my containerised fork at https://github.com/aaccioly-open-source/haven if you need a fully functional reference with all the bells and whistles.
Thanks for the quick response, but even though I specified NixOS and NGINX, as shown via curl, I don't think it's an issue related to those two.
Curl fails on a direct connection to Haven launched standalone from the build dir, executed as
curl -v --http1.1 -H "Connection: close" \
-H "Host: localhost" \
-H "X-Real-IP: 127.0.0.1" \
-H "X-Forwarded-Host: localhost" \
-H "X-Forwarded-For: 127.0.0.1" \
-H "X-Forwarded-Proto: https" \
-H "Connection: upgrade" \
-H "Upgrade: websocket" \
-H "Host: localhost" \
-H "X-Forwarded-Server: localhost" \
-H "Accept: */*" \
http://127.0.0.1:21498
Which seems to me to fully reflect the documentation. That's why I opened an issue here; I don't see any problems on the NGINX or NixOS, even though I'm reporting them for context. The above curl example mimic an NGINX setup exactly as per documentation AFAIK, if I remove -H "Upgrade: websocket" works but, obviously no Nostr client will work in that case.
I grabbed for confirmation the headers via tcpdump -i lo -n -A port 21498 to be extra sure.
Got it. In your shoes, I would check that you are not chasing a red herring with those curl requests. If the HTTP layer is working correctly, chances are the WebSocket layer is working as well.
There is a lot going on in a Nostr REQ or Event beyond simply upgrading HTTP connections to WebSockets. Sending an empty request using curl and receiving a “bad request” status code does not mean that your Haven instance is not working. It only means that Haven does not accept an empty request as valid. You might want to point a real Nostr client at your relay to be sure. E.g. https://github.com/fiatjaf/nak works great for local tests
For example, assuming you have RELAY_PORT=21498 in your .env and that you have run ./haven import to bring a copy of the relay owner’s notes into Haven and later started Haven, what is the output of?
nak req -k 1 --limit 1 ws://localhost:21498
To give a bit of context: I discovered Nostr very recently and decided to give a try. After just skimming through what it's supposed to be and do, I looked for a relay to self-host, and for some reason stumbled upon Strfry. I have a NixOS homeserver with the classic config in org-mode; there's a module ready for it, so I configure it and try it out. It works.
Strfry is a bit limited for just messing around as a total newbie like me, it doesn't have a Blossom server, for example, and I'd like to try that too. So I keep looking and come across Haven, which I really like on paper. It does everything in a single "app", it's written in Go (a language I like), and there's even a NixOS module for it, albeit a bit rough. I try simply swapping the Strfry babel block with the Haven one, keeping the config for NGINX, NFTables, ACME etc exactly the same. I'm basically just swapping one "backend" service for another. It installs correctly and starts up fine, but when I go to a Nostr client, I see the relay isn't working. I try accessing it simply through Firefox, expecting to find a "homepage," and I get a 400 Bad Request.
I take a look at the traffic passing through and pinpoint that specific header as the cause of the error. I rebuild with Strfry and the relay starts working again just like before, reverting back as expected does not. From this, I conclude (without further proof) that the problem must be on Haven's side since NGINX config is essentially the same as per Havend docs. Since the NixOS module is pretty bare-bones, I try cloning the repo and compiling from there; here too, everything seems to work until I actually try to use it, same error... That's how I ended up here, not knowing what else to do. To respond to the suggestion of testing with nak:
nak req -k 1 --limit 1 wss://nostr.domain.tld
wss://nostr.domain.tld... status 400
failed to connect to any of the given relays.
nak req -k 1 --limit 1 ws://127.0.0.1:21498
ws://127.0.0.1:21498... ok.
Monitoring (tcpdump -i lo -n -A port 21498) the request from localhost, I get
Upgrade: websocket
Connection: upgrade
Host: nostr.domain.tld
X-Real-IP: XXX.XXX.XXX.XXX
X-Forwarded-Host: nostr.domain.tld
X-Forwarded-For: XXX.XXX.XXX.XXX
X-Forwarded-Proto: https
Upgrade: websocket
Connection: upgrade
Host: nostr.domain.tld
X-Real-IP: XXX.XXX.XXX.XXX
X-Forwarded-For: XXX.XXX.XXX.XXX
X-Forwarded-Proto: https
X-Forwarded-Host: nostr.domain.tld
X-Forwarded-Server: srv
User-Agent: nak/s
Sec-Websocket-Extensions: permessage-deflate
Sec-Websocket-Key: AKey....==
Sec-Websocket-Version: 13
Accept-Encoding: gzip
....
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
Connection: close
400 Bad Request
just to show
nak event -c 'testing relay' wss://nostr.domain.tld
wss://nostr.domain.tld... failed to connect: error opening websocket to 'wss://nostr.domain.tld': failed to WebSocket dial: expected handshake response status code 101 but got 400
nak event -c 'testing relay' ws://127.0.0.1:21498
ws://127.0.0.1:21498... ok.
{"kind":1,"id":"299...
And I know "as per docs" and since they work with strfry that NGINX/ACME etc are formally ok. I'm trying to import now changing haven port and activating both but even if it will work it doesn't solve the primary issue which is how to connect from a nostr client... I understand that an empty request is not what a client do, but from localhost the empy request without "Upgrade: websocket" header to return the Haven homepage as expected and so do (also with the aforementioned header) with strfry, I assume then that's still an expected behavior...
the primary issue which is how to connect from a nostr client...
ws://127.0.0.1:21498... ok.
You are already connecting from a real Nostr client (nak), and it looks like it is working when you connect to Haven. nak is no different from any other Nostr client. If you expose port 21498 to your LAN and use another client such as Amethyst, Jumble, etc., they will also work. nak would not work if Haven itself were not able to upgrade HTTP connections to WebSockets.
If you want to further convince yourself that Haven is indeed working, create and publish an event with the relay owner’s real key:
nak event --sec nsecXXX -c 'testing relay' ws://127.0.0.1:21498
If you query it again, your event will be there:
nak req -k 1 --limit 1 ws://127.0.0.1:21498
As for this:
nak event -c 'testing relay' wss://nostr.domain.tld
wss://nostr.domain.tld... failed to connect: error opening websocket to 'wss://nostr.domain.tld': failed to WebSocket dial: expected handshake response status code 101 but got 400
The combination of Haven working when you connect directly to it, but failing to properly switch protocols and complete the handshake when you connect through the reverse proxy, points to something at the reverse proxy, firewall, or DNS layer. The sum of your troubleshooting efforts so far strongly suggests something in your Nginx setup. Maybe something that strfry tolerates but Haven does not, something in NixOs NginX defaults, or in the specific version of Nginx that NixOS is using. Unless someone else that understands both Haven and NixOS jumps in to help, as frustrating as it is, there's nothing that I can do on my side by looking at your curl requests and tcdump.
Even in a scenario where there's a legit issue beyond configuration that affects Haven and Nginx on NixOS, as much as I would like to help you, you are unfortunately on your own to narrow down the issue and potentially contribute the fix. But I want to reinforce that, after having troubleshooting many, many, many Haven setups broken in equally misterious ways, chances are that yours is a configuration issue.
I already gave you some options to troubleshoot the nginx reverse proxy configuration by dumping your configuration with nginx -T and comparing it to the docs or the configuration generated by my Nginx powered Docker fork linked above. Try stripping down your Nginx configuration to the bare minimum and figure out what is different compared to the docs.
Other than the configuration, look at the Nginx logs as well. Maybe some Nginx defaults are tightening something up or applying an optimisation directive that Haven does not like. E.g., what are default = true and proxyWebsockets = true doing with Nginx config? (running nginx -T with and without these options will answer this). I do not know what NixOS defaults are, or what those directives do, so it is really difficult to say anything one way or another. Digging down into raw nginx config and logs will likely help your troubleshooting.
Another option, if you really cannot get Nginx to work, is to try other reverse proxies like Apache or Caddy. One of them might be easier to set up on NixOS. Alternatively, you can take the fully dockerised setup linked above for a spin and bypass setting up the reverse proxy altogether.
Here’s a long shot, low risk change that may be worth trying. While googling your issue, I came across https://discourse.nixos.org/t/caliber-web-with-reverse-proxy/25031/3. Given that Nginx on NixOS does not like forwarding traffic to software bound to ::1, it may also dislike 0.0.0.0. In Go, binding to 0.0.0.0 can also end up exposing the server over IPv6 (see https://github.com/golang/go/issues/48723).
Maybe try changing Haven’s RELAY_BIND_ADDRESS to 127.0.0.1, then restart Haven and Nginx, and see what happens.
Thanks again for your time and effort, I've compared them and honestly are essentially the same
server {
listen 0.0.0.0:443 ssl default_server ;
listen [::0]:443 ssl default_server ;
server_name nostr.domain.tld ;
# this is the first substantial difference but AFAIK meaningless
# since for the proxy is set proxy_http_version 1.1;
http2 on;
ssl_certificate /var/lib/acme/nostr.domain.tld/fullchain.pem;
ssl_certificate_key /var/lib/acme/nostr.domain.tld/key.pem;
ssl_trusted_certificate /var/lib/acme/nostr.domain.tld/chain.pem;
location ^~ /.well-known/acme-challenge/ {
root /var/lib/acme/acme-challenge;
auth_basic off;
auth_request off;
}
location / {
proxy_pass http://127.0.0.1:21498;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# these are the extras NixOS default injected
proxy_set_header Connection $connection_upgrade;
proxy_set_header X-Forwarded-Host $host;
}
location /.well-known/nostr.json {
index nostr.json;
root /var/www/nostr;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';
}
location /favicon.ico {
index favicon.ico;
root /var/www/nostr;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';
autoindex off;
}
}
http2 is meaningless since proxy_http_version 1.1;, proxy_set_header Connection $connection_upgrade; it's just a soft version of proxy_set_header Connection "upgrade"; so it's meaningless there because "upgrade" force to upgrade anyway, proxy_set_header X-Forwarded-Host $host; again it's meaningless since proxy_set_header Host $host; AFAIK. Added locations are just to serve my nostr profile and relays + setting the favicon if someone visit the relay directly via a browser, I think they can't interfere.
RELAY_BIND_ADDRESS is "127.0.0.1"; from the start since it's behind NGINX, I've also tried to disable IPv6 for NGINX but nothing changes. I tried to stop NGINX and re-run it manually with a reduced config stripping extra meaningless configs and nothing changes as well.
Default means just that this vhost is the default one for the give (sub)domain, I stripped it now but... proxyWebsockets = true; just add duplicate proxy headers config which are already there, so are ignored by NGINX, more precisely
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
I'll try a bit more also with the NGINX NixOS module maintainer, so far I really can't see anything strange and all other services I test on the same system (Matrix, XMPP/Prosody, Coturn etc) are proxy-ed correctly as well.
I'll be back if I solve in a way or another, for now thanks again.
No problem. Yes, this is a weird one. I see nothing wrong either.
Http 2 at the Nginx level is fine, my container is also using it.
Have you tried to start nginx listening in port 80 + temporarily disable the whole ACME + https stuff as well as duplicated headers just in case? Just asking because the containerised version had some trouble with it when Let's Encrypt killed support for Must Staple.
Also, since RELAY_BIND_ADDRESS is 127.0.0.1 from the start start maybe try the other way around and go with 0.0.0.0, or to your box IPv4 IP (test with nak going to ws://your.server.public.ip:[your Haven port] as well).
Binding Haven to 0.0.0.0 on its own port works,
nak req -k 1 --limit 1 ws://nostr.domain.tld:21498
ws://nostr.domain.tld:21498... ok.
but proxying it through NGINX on port 80 doesn't, same error
nak req -k 1 --limit 1 ws://nostr.domain.tld
ws://nostr.domain.tld... failed to connect: error opening websocket to 'ws://nostr.domain.tld': failed to WebSocket dial: expected handshake response status code 101 but got 400
failed to connect to any of the given relays.
I've also written to the Haven NixOS module maintainer, so far I have really no idea. Manually cleaning NGINX config (meaning copy the NixOS generating one and strip anything irrelevant/duplicated then starting NGINX manually with the cleaned up file) does not change anything...
While you wait for Nginx module maintainers to come back, you may as well try Caddy, it should (I think) handle, SSL Certificates, Client IP Forwarding and WebSockets on its own (following is untested) :
services.caddy = {
enable = true;
virtualHosts."nostr.domain.tld".extraConfig = ''
request_body {
max_size 100MB
}
reverse_proxy http://127.0.0.1:21498 {
transport http {
versions 1.1
}
}
'';
};
networking.firewall.allowedTCPPorts = [ 80 443 ];
Or use the docker version linked above that uses the latest Alpine's Nginx package and bypasses NixOS quirks altogether.
I finally solved thanks to the module maintainer: apparently for unknown reasons (to me, at least) proxy_set_header Connection "upgrade"; cause the issue, the default "gentle" version proxy_set_header Connection $connection_upgrade; works.
Anyway thanks for your time and patience, it effectively is a Nix-related issues not a Haven one!
I've not tried Caddy so far because I have too much stuff under NGINX to migrate, I'll do in the near future though planning for a bit of NixOS Wiki page for Haven.