Custom domains for Multi-tenant web app - heroku

I am developing an app (RoR + Heroku) which allows users create their own websites either using my subdomain (pagename.myapp.com) or using their own domain (pagename.com).
An important point of this is that this option is the key of my business: subdomains are the free plans and custom domains are the paid ones. So I have a table where I store the custom domains of each user and check if this page is active (exists and has paid the quota).
For that I need to give users the capability of point their domain to my servers. All we know that Heroku don't recommend the use of DNS A-Records.
Also I would like to abstract as much as possible this feature to being able to switch my infrastructure (Heroku to AWS) in the future without having to ask all my users to change their DNS Zone. Taking this into account, I think that the best option would be run something like an EC2 proxy (using AWS Elastic IP) which give me the ownership of this IP. This proxy I think that should redirect to proxy.myapp.com, and I would resolve the request in the app level.
Due to I didn't find clear information about that, I am not sure if this hypotesis is the best solution and how to setup the proxy (which type of proxy use? Nginx maybe?).
Said that, I would like to ask recommendations/best practices to solve this "common" feature.
Thanks

What you are wanting to do is fairly straight forward to implement. Your assumptions are correct about setting up the proxy. Nginx or haproxy will both work great for this (I personally would use haproxy). Here are some of the gotchas that you will run into though:
Changing the host header at a proxy server can cause the end web application to generate incorrect links. You can use relative paths to fix this, but it requires that the web application developer to be aware of the environment that they are running in.
user connects to www.example.com (proxy server)
proxy server connects to www.realdomain.com (web app)
the web app has a link for a shopping cart. www.realdomain.com/shoppingcart
the end user clicks on the link but the link is www.realdomain.com/shoppingcart instead of www.example.com/shoppingcart
The cost of the host acting as the proxy server. This can spiral out of control really quickly. For example, do you want redundancy, if so how are you planning on implementing that? Do you plan on having ssl termination? If so you will have to increase the CPU count to accommodate the additional load. Do you want to have a secure connection to heroku from your proxy? If you do then you will need to increase the CPU count for that as well. You may have to add additional ram as well depending on the number of concurrent connections.
Heroku also changes their load balancers regularly. This is important because your proxy service will need to reload the config / update the ip addresses of the heroku instances every 60 seconds. In my experience they may change once or twice a day, but the DNS entry that they use has a 60 second TTL. That means that you should make sure that you are capable of updating your config up to every 60 seconds.
My company has been doing something very similar to this for almost a year now. We use haproxy and simply have it reload the config regularly. We have never had an outage or an interruption to our end users. Nginx is also a very good product. It has built in DNS caching so if you go that route you will need to make sure that you configure it correctly so that the DNS cache TTL is 60 seconds.

Will many of your clients want to use your app on their domain apex? E.g. example.com rather than theapp.example.cpm? If not, I would recommend having them CNAME to proxy.myapp.com which CNAMEs to myapp.herokuapp.com. Then, you can update proxy.myapp.com without customer interruption.
If you do need apex or A record support, you would want to set up Nginx as a reverse proxy for your Heroku app. Keep in mind that if you need HTTPS support for client domains, you will need to do some sort of certificate management on your proxy.

I like the answer dtorgo gave and that he mentioned the TLS termination, which many online tutorials on custom domains don't touch at all.
I'll go into more detail on how to implement the custom domains feature for your SaaS while also handling the TLS/HTTPS.
If your customers just CNAME to your domain or create the A record to your IP and you don't handle TLS termination for these custom domains, your app will not support HTTPS, and without it, your app won't work in modern browsers on these custom domains.
You need to set up a TLS termination reverse proxy in front of your webserver. This proxy can be run on a separate machine but you can run it on the same machine as the webserver.
CNAME vs A record
If your customers want to have your app on their subdomain, e.g. app.customer.com they can create a CNAME app.customer.com pointing to your proxy.
If they want to have your app on their root domain, e.g. customer.com then they'll have to create an A record on customer.com pointing to your proxy's IP. Make sure this IP doesn't change, ever!
How to handle TLS termination?
To make TLS termination work, you'll have to issue TLS certificates for these custom domains. You can use Let's Encrypt for that. Your proxy will see the Host header of the incoming request, e.g. app.customer1.com or customer2.com etc., and then it will decide which TLS certificate to use by checking the SNI.
The proxy can be set up to automatically issue and renew certificates for these custom domains. On the first request from a new custom domain, the proxy will see it doesn't have the appropriate certificate. It will ask Let's Encrypt for a new certificate. Let's Encrypt will first issue a challenge to see if you manage the domain, and since the customer already created a CNAME or A record pointing to your proxy, that tells Let's Encrypt you indeed manage the domain, and it will let you issue a certificate for it.
To issue and renew certificates automatically, I'd recommend using Caddyserver, greenlock.js, OpenResty (Nginx).
tl;dr on what happens here;
Caddyserver listens on 443 and 80, it receives requests, issues, and renews certificates automatically, proxies traffic to your backend.
How to handle it on my backend
Your proxy is terminating TLS and proxying requests to your backend. However, your backend doesn't know who is the original customer behind the request. This is why you need to tell your proxy to include additional headers in proxied requests to identify the customer. Just add X-Serve-For: app.customer.com or X-Serve-For: customer2.com or whatever the Host header is of the original request.
Now when you receive the proxied request on the backend, you can read this custom header and you know who is the customer behind the request. You can implement your logic based on that, show data belonging to this customer, etc.
More
Put a load balancer in front of your fleet of proxies for higher availability. You'll also have to use distributed storage for certificates and Let's Encrypt challenges. Use AWS ECS or EBS for automated recovery if something fails, otherwise, you may be waking up in the middle of the night restarting machines, or your proxy manually.
If you need more detail you can DM me on Twitter #dragocrnjac

Related

Deploying an Internal API

I basically have an API that is going to be used with a web app and a mobile app. I don't want the API to publically available, where should I deploy it then? is there a way without using AWS? Thanks, Nav :)
There are multiple ways of doing this. This is a sensitive topic, as this is an opinion-based field.
However, I will try to answer below - and challange your way of approaching this.
It really depends on your 'operational' skills, funds, need for security, deadline(s) etc.
Basically you need to make an endpoint available on the www, without everybody being able to connect.
You could either:
Deploy a virtual machine or web app. in Azure/AWS/GCP/... and whitelist the IP's you need to connect from.
Rent a VPS from any provider, and deploy your application here - Again, whitelisting. (Edit: Not phones, since this IP changes constantly. A proxy can be implemented here (potential bottleneck), or any authentication mechanism like OAuth, JWT, Certificates etc. can be implemented either on the ingress controller (e.g. NGINX) or the application itself.)
Deploy the application on your Home-PC, order a static IP to your home and make a forwarded port and set up security on your premise (not recommended, and raises and bunch of other headaches)
Get in touch with a company that hosts web applications (Can be quite expensive)
Based on the limited information provided in your question, there is a ton of options, nice-2-haves and factors that comes in to play when choosing the setup that suits your needs.
You should also consider; VPN usage, Backup/disaster recovery, data leaks, redundancy, the need for future deploys, how you would access your environment in six months....
I hope this answered your question, but also raised a few for you to answer yourself.
Finally, I'd recommend you looking for inspiration here.
EDIT:
Question:
Whitelisting mobile IP's.
VPS selected.
Answer:
This becomes quite a task when mobile phones tend to change IP's frequently.
Since you are looking further into the VPS setup, you are more in control of the setup and can choose to look into OAuth and JWT.
Links:
OAuth - https://oauth.net/getting-started/ https://developer.okta.com/blog/2019/01/22/oauth-api-keys-arent-safe-in-mobile-apps
NGINX JWT - https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-jwt-authentication/
So - At the end of the day, you can make your app use a proxy (potential bottleneck) and whitelist this IP, or make the endpoint open (any -> 443) and implement an authentication mechanism like the ones mentioned above.
Consider implementing a DMZ zone for incoming traffic from the web.
https://en.wikipedia.org/wiki/DMZ_(computing)
and put your application behind this zone, making sure that the only the DMZ zone is facing the internet, and the server hosting your application is talking to the server in the DMZ.
Again, this is quite a big topic and is hard to simplify to a stackoverflow post.
If you are hosting the app on AWS you have a couple of options.
API Gateway now supports private endpoints. These endpoints can not be called via the public internet. That means if your app is hosted on AWS only the internal services of the app can call the end point. i.e. front end to database etc. I've used this method for internal micro services such as placing in house app data onto kinesis streams.
Alternatively, if you don't want to use API Gateway you have lots of options. Most of which would involve you creating rest APIs from where ever you plan on hosting your code. This could be on the server it's self or some sort of container.
API Gateway Private Endpoint Reference:
https://aws.amazon.com/blogs/compute/introducing-amazon-api-gateway-private-endpoints/

How to use Azure Traffic Manager with a custom domain, if the DNS settings don't allow for forwarding

I have an Azure web app up and running, using a custom domain purchased outside of Azure... and that all runs fine. So I have https://myappname.azurewebsites.net/ loading fine with my domain name URL https://www.myappname.com
I'm trying to upgrade the web app, though using Azure Traffic Manager. I've cloned the app a few times, each on its own app service plan, and I have the traffic manager all up and running fine. I can successfully hit different versions of my cloned website based on the traffic manager configuration profile... so no issues there.
The only issue is that I can only access the "traffic managed" version of my website via the standard azure URL -> myappname.trafficmanager.net.
All examples I've seen say all I really need to do now, is go into my DNS Management screen, and add domain forwarding, however, my online DNS management tool does not offer this option.
I can't really change my A record in the DNS management screen, because I don't know the IP address of myappname.trafficmanager.net
Every place I've tried to change the name of the current/working Azure URL (like in awverify text files, www cnames, etc.) does nothing. The DNS still points to the single instance which remains in the IP address od the DNS managers A record.
Also, since my live/single instance is linked to the domain name (along with the SSL binding), I can't add those properties to the clones, which makes sense....only one version can be live. However I could unbind that when I make the switch from the single instance web app to the traffic managed set of clones, but I fear I can only bind that to one of the clones. I can't seem to bind it to the myappname.trafficmanager.net version, which might cascade down to all of its endpoints. Is there a way to bind my domain name and SSL cert to more than one version of my web app?
Thanks!
Is there a way to bind my domain name and SSL cert to more than one
version of my web app?
I don't think you can do that unless you have two different domains or subdomains with each own SSL cert. Each web app hostname is unique globally and each SSL binding is attached with the web app domain name.
If you have a purchased domain and just keep the default xxx.azurewebsites.net as each hostname. Then you could configure the two Azure app serves as the endpoint of TM.
By default, Azure provided a wildcard cert for this domain *azurewebsites.net, so you can automatically access this hostname with HTTPS without any extra cert. Then use a CNAME record www in the domain domain.com in your DNS provider to point to the traffic manager hostname myappname.trafficmanager.net. Since Traffic Manager works as DNS level, it does not validate the server and client SSL, you could safely ignore the SSL warning when accessing with traffic manager hostname.
Feel free to let me know if you have any question.

Sharing sessions between different servers behind an nginx reverse proxy

Wondering if we can share session data between two servers (running different code) behind an Nginx reverse proxy.
To be precise, we have a legacy app in PHP running on an apache server. We are updating some functionality and hosting only that functionality on a separate server (nginx). Both apps update the same DB.
nginX uses load balancing/ reverse proxy URL rewritting techniques to decide which server to send the client to based on the URL path they use.
So, a person can add items to his virtual basket (held in session) on
the new server application.
He then decides to edit his personal information which is on the other server (Legacy).
Nginx uses it's reverse proxy/load balancing magic to decide which server to send the person to based on where an app is available.
The question is, how can a session created on one app server be available to another app server aswell? is it possible to setup the reverse proxy to store all session data and how. Please point me to the right direction of you can help with google links aswell.
your question has several possible answers. It all depends on the way the application is designed.
A possible scenario would be to keep session information on a database shared among different web heads. In this way the client, once authenticated will retrieve its "session status" regardless which server he is accessing in the final servers cluster backend.
Again, this depends very much on the way the application is/has been designed.
I think there is very little magic you can do on an old legacy application just by configuring the reverse proxy engine.
In the end, sessions are handled by the application server and not the proxy frontend.

Heroku & DNS: Can http://nakeddomain.com aim at my heroku app?

So, I've been reading quite some content about this. The latest one being here, and the heroku doc.
At the end, nobody answers the question clearly:
Is it possible to have http://nakeddomain.com aiming at a heroku app?
Here's what I know:
It is easy to redirect http://nakeddomain.com to http://www.nakeddomain.com to CNAME http://myapp.herokuapp.com : I don't want to do that
It is sometimes possible to ANAME (or ALIAS, or CNAME depending on the DNS provider vocabulary) apex name to another record. But in that case, all records are CNAMEd or ANAMEd (even the MX for mail delivery) which makes mail#nakeddomain.com unroutable as redirected to heroku app which certainly doesn't handle it by default.
So I'm going to reformulate
Is it possible to have http://nakeddomain.com aiming at a heroku app while using mails#nakeddomain.com?
How? Which services to use?
How much does it costs if there are extras to pay?
Should I stick on CNAMing apex name and move the mailer to another service (Google Apps, or Sendgrid as some suggest in Stackoverflow) or is it making it worse?
Subsidary questions:
Been reading Cloudflare is quite nice. How does it help me?
We are using 1and1 as a DNS provider currently? Does it make it easier/harder anyhow?
Been also reading DNSimple allows more features than other DNS providers. Which one?
Since we send automatic mails from our app, SPAM filtering is also a concern from mails#nakeddomain.com, if that has to do with the required configuration.
Thanks for support
Apex domains have no impact on using the naked domain for emails - completely different types of record. I have domains using DNSimple CNAMEs and the same domain for email. One is a cname, the other is an MX reocrd.
I would suggest using DNSimple or the cheaper option DNS made easy - both support ALIAS records, with the $30 a year plan you get 10 domains. I typically using one or the other and Google Apps for email which works just fine. For applications to send email I use Sendgrid.
CloudFlare is a caching layer. To use them you have to move your DNS to them.
You can use 1&1 as your registrar but you then use one of the previously mentioned to host the DNS - they have far superior services. Both provide CNAME but also redirection at DNS level so you can have www.domain.com redirected to domain.com at DNS level and not in your application. If you use Sendgrid for sending emails I'm sure they have a SPF record you can put on your domain to help keep emails out of spam folders.
EDIT:
Cloudflare seems to be the good solution for me: brings CDN and naked domain through changing DNS servers to their own and they have a free plan.
I'm going to answer point by point to explain what I've done:
Is it possible to have http://nakeddomain.com aiming at a heroku app while using mails#nakeddomain.com?
Yes
How? Which services to use?
Only using DNSimple or DNS made easy, as they handle ALIAS/ANAME records.
How much does it costs if there are extras to pay?
Cheapest is DNS made easy with $30/year
Should I stick on CNAMing apex name and move the mailer to another service (Google Apps, or Sendgrid as some suggest in Stackoverflow) or is it making it worse?
Haven't explored this option much, but if your domain provider has decent mail services, no reason to move out of it. It probably costs more money for this service...
Subsidary questions:
Been reading Cloudflare is quite nice. How does it help me?
Finally did not end up using it...
We are using 1and1 as a DNS provider currently? Does it make it easier/harder anyhow?
1and1 doesn't have ALIAS/ANAME records. So I had to use extra service (DNS made easy in my case), they give you a list of dns hosts that need to be replaced in the 1and1 interface and then it takes care of the rest.
Careful: For beginners reading this, updating these entries won't assign changes all over the web at once as DNS is based a lot on caching. You need to take this in account when doing changes, if you have production services. You could end up with weird behaviors between like infinite redirects, cdn not properly redirecting, or OAuth redirects broken for a while ...
Been also reading DNSimple allows more features than other DNS providers. Which one?
More customization is possible with DNS made easy. Interface will be more user-friendly also.
Eg. 301 redirects instead of 302 for 1and1, PTR records and other newest DNS records
Since we send automatic mails from our app, SPAM filtering is also a concern from mails#nakeddomain.com, if that has to do with the required configuration.
I read PTR records were good to prevent SPAM, but as far as I understood, it doesn't make sense when using heroku because the whole point of this record is to aim IP-Address to nakeddomain.com which is not possible as heroku doesn't provide fixed IP-addresses.
Hope it helps.

Not sure how to set up my dns and heroku apps to do what I want

Heroku offers US and EU servers and I want my users to connect to the server which is closer to them, so if someone connects from the EU, I will redirect them to the EU server and the same for the US.
My idea was to have them connect to main domain name, example.com that would connect to the US server, which would check where the users are coming from, and then redirect them to where I want them to be, and all this while they are looking at the same domain "example.com". Heroku wont let me add the same domain twice, and I don't know where I should configure what for the DNS. My domain provider has a nameserver section and I'm not sure what to add there. Basically I want all the request and server load to go onto the Heroku page, and not onto the default DNS server which only redirects or loads the Heroku page inside a frame.
They way it seems correct, is to connect to example.com, which is the US Heroku page and then redirect inside a frame or something to the EU page... not sure if this is the best way, and like I mentioned, I'm not sure how to setup the namespace and stuff so they connect directly to the Heroku server instead of the default domain server.
Could someone explain to me what I need to do to achieve what I want?
It is currently not possible to run a multi-region application on Heroku and I'd caution against trying to work your way around this limitation. Some areas that cause users problems when trying to attempt this are:
You can't have the same custom domain on two apps (as you've already identified).
There is no way to setup a multi-master database configuration so each app has a db in its own region. Likewise, maintaining a single master for both apps results in very high latency for one of the apps.
The connection overhead of any other trickery, like what you propose here, often negates any latency improvement the user sees from accessing the app in their closest region.
Using a CDN for static assets, and having a proper http cache header strategy often gets you 90% of the way to the performance of a truly geo-distributed app.
To drill further into your question, I'm not sure what you mean here?
how to setup the namespace and stuff so they connect directly to the Heroku server instead of the default domain server
Hope that helps!

Resources