This post is for those that have a reverse proxy, such as nginx, in front of their Home Assistant and want to get Telegram webhooks working with it. I’m not sure if this is a workaround or a solution, but either way, it works well!
Over the past few days, I’ve been learning how a reverse proxy (in my case, nginx) works. Slowly but surely, I’ve been getting pieces of HA working well behind that proxy. Today’s hurdle was Telegram.
Whenever the webhooks side of Telegram tried to do something, the HA logs would report that access is denied for the IP address of the machine on which I had nginx running. The problem—that (local) IP address is not in the list of trusted_networks
for the Telegram component. While tempting, it would not be secure to simply add that address to the list because all requests (including those of nefarious hackers) will be seen as coming from that address!
The way I handled this is to not only add the local IP address of the nginx machine to the trusted_networks
in the Telegram component, but ALSO add a location filter to the nginx configuration.
An example entry for your configuration.yaml
:
telegram_bot:
- platform: webhooks
api_key: YOUR_TELEGRAM_API_KEY
url: https://YOUR_SUB_DOMAIN.duckdns.org # Or whatever your domain is
trusted_networks:
- 149.154.167.197/32 # I don't think these telegram IPs are needed here anymore
- 149.154.167.198/31
- 149.154.167.200/29
- 149.154.167.208/28
- 149.154.167.224/29
- 149.154.167.232/31
- YOUR_NGINX_LOCAL_IP # the pertinent addition
allowed_chat_ids:
- YOUR_CHAT_IDS
For your nginx configuration, add this:
location /api/telegram_webhooks {
proxy_pass http://YOUR_LOCAL_HA_IP_ADDRESS:8123/api/telegram_webhooks;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
allow 149.154.167.197/32;
allow 149.154.167.198/31;
allow 149.154.167.200/29;
allow 149.154.167.208/28;
allow 149.154.167.224/29;
allow 149.154.167.232/31;
deny all;
}
So, you see, we let nginx take care of allowing only the trusted networks, and we can safely add the local IP address of the nginx machine to the trusted_networks
of HA’s configuration.
If anyone knows of a better way to do this or sees something I missed, please feel free to post here. I just got this working now and wanted to share it with any future experimenters.