├── .env_example
├── .github
└── workflows
│ └── docker-image.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── app
├── __init__.py
├── api.py
├── caddy
│ ├── __init__.py
│ ├── caddy.py
│ ├── caddy_config.py
│ └── saas_template.py
├── main.py
└── security.py
├── docker-compose.yml
├── domains
└── .gitignore
├── entrypoint.sh
├── main.py
└── requirements.txt
/.env_example:
--------------------------------------------------------------------------------
1 | SAAS_UPSTREAM=example.com:443
2 | API_KEY=0df05a6c-d4c6-4ee4-a55d-de1409e82cee
--------------------------------------------------------------------------------
/.github/workflows/docker-image.yml:
--------------------------------------------------------------------------------
1 | name: Docker Image CI
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 |
7 | jobs:
8 |
9 | build:
10 |
11 | runs-on: ubuntu-latest
12 |
13 | steps:
14 | - uses: actions/checkout@v3
15 | - name: Build the Docker image
16 | run: docker build -t ${DOCKER_REGISTRY}/${IMAGE}:latest .
17 | env:
18 | DOCKER_REGISTRY: docker.io
19 | IMAGE: sireto/custom-domain
20 | - name: Login to Docker Registry
21 | run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin ${DOCKER_REGISTRY}
22 | env:
23 | DOCKER_REGISTRY: docker.io
24 | - name: Push the Docker image
25 | run: docker push ${DOCKER_REGISTRY}/${IMAGE}:latest
26 | env:
27 | DOCKER_REGISTRY: docker.io
28 | IMAGE: sireto/custom-domain
29 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /local/
2 | /venv/
3 | .idea/
4 | .env
5 | __pycache__/
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8
2 | RUN apt update
3 | RUN apt install -y debian-keyring debian-archive-keyring apt-transport-https
4 | RUN curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
5 | RUN curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list
6 | RUN apt update && apt install -y caddy
7 |
8 | COPY ./app /app/app
9 | COPY ./domains /app/domains
10 | COPY ./requirements.txt /app/requirements.txt
11 | COPY ./entrypoint.sh /app/entrypoint.sh
12 |
13 | WORKDIR /app
14 | RUN pip3 install -r requirements.txt
15 |
16 | CMD ["/app/entrypoint.sh"]
17 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Custom Domain API
2 | This service is designed to support custom domains for SaaS products.
3 |
4 | # Usage
5 | Here are the steps you need to take to run this docker image.
6 |
7 | ## 1. Environment variables
8 | Set the proper environment variable for your desired installation.
9 |
10 | Here is a sample `.env` file.
11 | ```
12 | SAAS_UPSTREAM=example.com:443
13 | API_KEY=0df05a6c-d4c6-4ee4-a55d-de1409e82cee
14 | ```
15 |
16 | ## 2. Create docker volumes to persist data (eg. certificates, domains etc.)
17 | ```bash
18 | docker volume create https_data
19 | docker volume create https_domains
20 | ```
21 |
22 | ## 3. Docker Compose file
23 | Create a `docker-compose.yml` file.
24 | ```yaml
25 | version: "3.7"
26 |
27 | services:
28 | https:
29 | image: sireto/custom-domain:latest
30 | ports:
31 | - "80:80"
32 | - "443:443"
33 | - "443:443/udp"
34 | - "9000:9000"
35 | restart: unless-stopped
36 | networks:
37 | - frontend
38 | env_file:
39 | - .env
40 | volumes:
41 | - https_domains:/app/domains
42 | - https_data:/root/.local/share
43 |
44 | volumes:
45 | https_data:
46 | external: true
47 | https_domains:
48 | external: true
49 |
50 | networks:
51 | frontend:
52 | ```
53 | Now you can run the compose file:
54 | ```bash
55 | docker-compose up -d
56 | ```
57 |
58 | This will run a webserver and the management APIs.
59 |
60 | The OpenAPI docs for the management APIs will be available on port 9000.
61 | So, if you deployed host is localhost, the APIs are available at:
62 | **http://localhost:9000/docs**
63 |
64 | ## 4. Instructions for SaaS customers
65 | Your SaaS customers need to add a DNS Record to point their domain to your deployed server. This can be done in one of the two ways.
66 | ### 4.1 A Record
67 | Assuming your deployed server has IP address: `XX.XX.XX.XX`.
68 | Then your customers will have to set the DNS Record:
69 | - Type: A Record
70 | - Name: customerdomain.com (or subdomain)
71 | - IPv4 address: `XX.XX.XX.XX`
72 |
73 | ### 4.2 CNAME Record
74 | Assuming your deployed server has a DNS name: `custom.example.com`
75 | Then, your customer should set the following DNS records:
76 | - Type: CNAME Record
77 | - Name: customerdomain.com (or subdomain)
78 | - Target: `custom.example.com`
79 |
80 | # Source Code
81 | The full source code is available on GitHub
82 | [**https://github.com/sireto/custom-domain**](https://github.com/sireto/custom-domain)
83 |
84 |
85 | # Paid version and Support
86 | Don't want to host it yourself? No problem! We do it for you. Here's what you get on the paid version:
87 | - Unlimited domains
88 | - A dedicated IP address
89 | - 20TB of free traffic
90 | - Webserver with 2GB RAM, 1vCPU
91 | - Email support
92 |
93 | **Price: $20 / month**
94 | **Contact: info@sireto.com**
--------------------------------------------------------------------------------
/app/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sireto/custom-domain/99220f0effac0541c140a6395aba1ffe18c54fa0/app/__init__.py
--------------------------------------------------------------------------------
/app/api.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | from fastapi import APIRouter, Depends
4 | from fastapi.openapi.models import APIKey
5 |
6 | from app.caddy.caddy import caddy_server
7 | from app.security import get_api_key
8 |
9 | """
10 | Domain API
11 | ===========
12 | GET /domains
13 | POST /domains?domain=&upstream=
14 | DELETE /domains?domain=
15 | """
16 | domain_api = APIRouter()
17 |
18 |
19 | @domain_api.get("/domains", tags=["Custom Domain API"])
20 | async def get_domains(api_key: APIKey = Depends(get_api_key)):
21 | return caddy_server.list_domains()
22 |
23 |
24 | @domain_api.post("/domains", tags=["Custom Domain API"])
25 | async def add_domain(domain: str,
26 | upstream: Optional[str] = None,
27 | api_key: APIKey = Depends(get_api_key)):
28 | caddy_server.add_custom_domain(domain, upstream)
29 | return "OK"
30 |
31 |
32 | @domain_api.delete("/domains", tags=["Custom Domain API"])
33 | async def remove_domains(domain: str,
34 | api_key: APIKey = Depends(get_api_key)):
35 | caddy_server.remove_custom_domain(domain)
36 | return "OK"
37 |
--------------------------------------------------------------------------------
/app/caddy/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sireto/custom-domain/99220f0effac0541c140a6395aba1ffe18c54fa0/app/caddy/__init__.py
--------------------------------------------------------------------------------
/app/caddy/caddy.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from dotenv import load_dotenv
4 | from fastapi import HTTPException
5 | import validators
6 |
7 | from app.caddy.caddy_config import CaddyAPIConfigurator
8 |
9 | HTTPS_PORT = 443
10 |
11 | DEFAULT_ADMIN_URL = 'http://localhost:2019'
12 | DEFAULT_CADDY_FILE = "domains/caddy.json"
13 | DEFAULT_SAAS_UPSTREAM = "example.com:443"
14 | DEFAULT_LOCAL_PORT = f"{HTTPS_PORT}"
15 |
16 | load_dotenv()
17 |
18 |
19 | class Caddy:
20 |
21 | def __init__(self):
22 | self.admin_url = os.environ.get('CADDY_ADMIN_URL', DEFAULT_ADMIN_URL)
23 | self.config_json_file = os.environ.get('CADDY_CONFIG_FILE', DEFAULT_CADDY_FILE)
24 | self.saas_upstream = os.environ.get('SAAS_UPSTREAM', DEFAULT_SAAS_UPSTREAM)
25 | self.local_port = os.environ.get('LOCAL_PORT', DEFAULT_LOCAL_PORT)
26 | self.disable_https = os.environ.get('DISABLE_HTTPS', 'False').upper() == "TRUE"
27 |
28 | self.configurator = CaddyAPIConfigurator(
29 | api_url=self.admin_url,
30 | https_port=self.local_port,
31 | disable_https=self.disable_https
32 | )
33 |
34 | if not self.configurator.load_config_from_file(self.config_json_file):
35 | self.configurator.init_config()
36 |
37 | def add_custom_domain(self, domain, upstream):
38 | if not validators.domain(domain):
39 | raise HTTPException(status_code=400, detail=f"{domain} is not a valid domain")
40 |
41 | upstream = upstream or self.saas_upstream
42 | if not self.configurator.add_domain(domain, upstream):
43 | raise HTTPException(status_code=400, detail=f"Failed to add domain: {domain}")
44 |
45 | self.configurator.save_config(self.config_json_file)
46 |
47 | def remove_custom_domain(self, domain):
48 | if not validators.domain(domain):
49 | raise HTTPException(status_code=400, detail=f"{domain} is not a valid domain")
50 |
51 | if not self.configurator.delete_domain(domain):
52 | raise HTTPException(status_code=400, detail=f"Failed to remove domain: {domain}. Might not be exist.")
53 |
54 | self.configurator.save_config(self.config_json_file)
55 |
56 | def deployed_config(self):
57 | return self.configurator.config
58 |
59 | def list_domains(self):
60 | return self.configurator.list_domains()
61 |
62 |
63 | caddy_server = Caddy()
64 |
--------------------------------------------------------------------------------
/app/caddy/caddy_config.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import time
3 |
4 | import requests
5 | import json
6 |
7 | from app.caddy import saas_template
8 | from app.caddy.saas_template import DomainAlreadyExists, DomainDoesNotExist
9 |
10 |
11 | class CaddyAPIConfigurator:
12 |
13 | def __init__(self, api_url, https_port, disable_https=False):
14 | self.logger = logging.getLogger(__name__)
15 | self.api_url = api_url
16 | self.config = {}
17 | self.https_port = https_port
18 | self.disable_https = disable_https
19 |
20 | def init_config(self):
21 | config = saas_template.https_template(disable_https=self.disable_https)
22 | if self.load_new_config(config):
23 | self.config = config
24 |
25 | def load_new_config(self, config):
26 | try:
27 | # Update the Caddy configuration using the /load endpoint
28 | headers = {"Content-Type": "application/json"}
29 | response = requests.post(f"{self.api_url}/load", headers=headers, data=json.dumps(config))
30 | response.raise_for_status()
31 |
32 | self.logger.info(f"Configuration has been loaded from config:\n{config}")
33 | self.config = config
34 | return True
35 | except requests.exceptions.HTTPError as e:
36 | self.logger.error(f"An error occurred while loading the configuration: {e}")
37 | self.logger.error(f"Response content: {response.content.decode('utf-8')}")
38 | return False
39 |
40 | def load_config_from_file(self, file_path):
41 | try:
42 | with open(file_path, 'r') as config_file:
43 | config = json.load(config_file)
44 | success = self.load_new_config(config)
45 | if success:
46 | self.config = config
47 | return success
48 | except FileNotFoundError as e:
49 | self.logger.error(f"An error occurred while loading the configuration: {e}")
50 | return False
51 |
52 | def save_config(self, file_path):
53 | try:
54 | # Fetch the entire Caddy configuration
55 | response = requests.get(f"{self.api_url}/config/")
56 | response.raise_for_status()
57 | config = response.json()
58 |
59 | # Save the configuration to a file
60 | with open(file_path, 'w') as config_file:
61 | json.dump(config, config_file, indent=2)
62 |
63 | self.logger.info(f"Configuration has been saved to {file_path}.")
64 |
65 | except requests.exceptions.HTTPError as e:
66 | self.logger.error(f"An error occurred while saving the configuration: {e}")
67 | self.logger.error(f"Response content: {response.content.decode('utf-8')}")
68 | return
69 |
70 | def add_domain(self, domain, upstream):
71 | try:
72 | config = self.config.copy()
73 |
74 | try:
75 | new_config = saas_template.add_https_domain(
76 | domain,
77 | upstream,
78 | template=config,
79 | port=self.https_port,
80 | disable_https=self.disable_https
81 | )
82 |
83 | # Try loading new config. If not successful, load the previous config
84 | if self.load_new_config(new_config):
85 | return True
86 |
87 | self.load_new_config(config)
88 | return False
89 |
90 | except DomainAlreadyExists as dae:
91 | self.logger.error(f"Domain '{domain} already exists somewhere else.")
92 | raise
93 |
94 | except requests.exceptions.HTTPError as e:
95 | self.logger.error(f"An error occurred while adding the domain '{domain}': {e}")
96 | raise
97 |
98 | def delete_domain(self, domain):
99 | try:
100 | config = self.config.copy()
101 |
102 | try:
103 | new_config = saas_template.delete_https_domain(domain, config, port=self.https_port)
104 |
105 | # Try loading new config. If not successful, load the previous config
106 | if self.load_new_config(new_config):
107 | return True
108 |
109 | self.load_new_config(config)
110 | return False
111 |
112 | except DomainDoesNotExist:
113 | self.logger.error(f"Domain '{domain} does not exist.")
114 | raise
115 |
116 | except requests.exceptions.HTTPError as e:
117 | self.logger.error(f"An error occurred while deleting the domain '{domain}': {e}")
118 | # self.logger.error(f"Response content: {response.content.decode('utf-8')}")
119 | raise
120 |
121 | def list_domains(self):
122 | try:
123 | # Fetch the entire Caddy configuration
124 | response = requests.get(f"{self.api_url}/config/")
125 | response.raise_for_status()
126 | config = response.json()
127 |
128 | # Add domain to match
129 | domains = saas_template.list_domains(config, port=self.https_port)
130 | return domains
131 | except requests.exceptions.HTTPError as e:
132 | self.logger.error(f"An error occurred while listing domains: {e}")
133 | self.logger.error(f"Response content: {response.content.decode('utf-8')}")
134 | return
135 |
136 |
137 | if __name__ == "__main__":
138 | CADDY_API_URL = "http://localhost:2019"
139 | SERVER_PORT = 443
140 | CADDY_FILE = "caddy.json"
141 |
142 | SAAS_UPSTREAM = "example.com:443" # this is where you SaaS should be available.
143 | DEV_UPSTREAM = "example.com:443"
144 |
145 | configurator = CaddyAPIConfigurator(CADDY_API_URL, SERVER_PORT, disable_https=False)
146 | if not configurator.load_config_from_file(CADDY_FILE):
147 | configurator.init_config()
148 |
149 | # Assuming these are customer domains you want to support
150 | custom_domains = [
151 | "customer1.domain.localhost",
152 | "customer2.domain.localhost",
153 | "customer3.domain.localhost",
154 | "customer4.domain.localhost",
155 | "customer5.domain.localhost",
156 | ]
157 |
158 | for custom_domain in custom_domains:
159 | configurator.add_domain(custom_domain, SAAS_UPSTREAM)
160 |
161 | # We want to save the config so the changes persist during restart
162 | configurator.save_config(CADDY_FILE)
163 |
164 | # To check if the custom domains are setup, checkout
165 | # https://customer1.domain.localhost
166 | # https://customer2.domain.localhost
167 | # and so on.
168 | #
169 | # Note that, we're using *.localhost for this local test. It is
170 | # because Caddy creates certificates for *.localhost domains.
171 | # If it is not working for you, then you might need to run
172 | # $ caddy trust
173 | #
174 | # This will install Caddy CA to your host operating system
175 | # and the HTTPS certificate will be trusted.
176 |
--------------------------------------------------------------------------------
/app/caddy/saas_template.py:
--------------------------------------------------------------------------------
1 | from typing import Dict, List
2 |
3 | HTTPS_PORT = 443
4 |
5 |
6 | def https_template(port=HTTPS_PORT, disable_https=False):
7 | return {
8 | "apps": {
9 | "http": {
10 | "servers": {
11 | f"{port}": {
12 | "listen": [
13 | f":{port}"
14 | ],
15 | "automatic_https": {"disable": disable_https},
16 | "routes": []
17 | }
18 | }
19 | }
20 | }
21 | }
22 |
23 |
24 | class DomainAlreadyExists(ValueError):
25 | pass
26 |
27 |
28 | class DomainDoesNotExist(ValueError):
29 | pass
30 |
31 |
32 | def add_https_domain(domain, upstream, port=HTTPS_PORT, template=None, replace=True, disable_https=False):
33 | if not template or not isinstance(template, dict):
34 | template = {}
35 | else:
36 | template = template.copy()
37 |
38 | apps = template.get("apps", None)
39 | if not apps:
40 | apps = {}
41 | template["apps"] = apps
42 |
43 | http = apps.get("http", None)
44 | if not http:
45 | http = {}
46 | apps["http"] = http
47 |
48 | servers = http.get("servers", None)
49 | if not servers:
50 | servers = {}
51 | http["servers"] = servers
52 |
53 | https_server = servers.get(f"{port}", None)
54 | if not https_server:
55 | https_server = {"listen": [f":{port}"], "routes": []}
56 | servers[f"{port}"] = https_server
57 |
58 | routes: List[Dict] = https_server.get("routes", [])
59 | expected_route = route_template(domain, upstream, disable_https=disable_https)
60 | exists = False
61 | for route in routes:
62 | for match in route.get("match", []):
63 | if domain in match.get("host", []):
64 | exists = True
65 | if replace:
66 | # replace the handle with expected route handle
67 | route["handle"] = expected_route["handle"]
68 | break
69 | raise DomainAlreadyExists(f"{domain} already exists")
70 |
71 | if not exists:
72 | routes.append(expected_route)
73 |
74 | return template
75 |
76 |
77 | def route_template(domain, upstream, disable_https=False):
78 | return {
79 | "handle": [
80 | {
81 | "handler": "subroute",
82 | "routes": [
83 | {
84 | "handle": [
85 | reverse_proxy_handle_template(upstream, disable_https=disable_https)
86 | ]
87 | }
88 | ]
89 | }
90 | ],
91 | "match": [
92 | {
93 | "host": [domain]
94 | }
95 | ],
96 | "terminal": True
97 | }
98 |
99 |
100 | def reverse_proxy_handle_template(upstream, disable_https=False, handle_id=None):
101 | if ":" not in upstream:
102 | upstream = f"{upstream}:{HTTPS_PORT}"
103 |
104 | handle = {
105 | "handler": "reverse_proxy",
106 | "headers": {
107 | "request": {
108 | "set": {
109 | "Host": [
110 | "{http.reverse_proxy.upstream.host}"
111 | ],
112 | "X-Real-Host": [
113 | "{http.reverse_proxy.upstream.host}"
114 | ],
115 | "X-Real-Ip": [
116 | "{http.reverse-proxy.upstream.address}"
117 | ]
118 | }
119 | }
120 | },
121 | "transport": {
122 | "protocol": "http",
123 | "tls": {}
124 | },
125 | "upstreams": [
126 | {
127 | "dial": upstream
128 | }
129 | ]
130 | }
131 |
132 | if disable_https:
133 | del handle["transport"]["tls"]
134 |
135 | if handle_id:
136 | handle["@id"] = handle_id
137 |
138 | return handle
139 |
140 |
141 | def delete_https_domain(domain, template, port=HTTPS_PORT):
142 | try:
143 | template = template.copy()
144 | routes = template["apps"]["http"]["servers"][f"{port}"]["routes"]
145 |
146 | removed = False
147 | for route in routes.copy():
148 | for match in route.get("match", []):
149 | if domain in match.get("host", []):
150 | routes.remove(route)
151 | removed = True
152 |
153 | if not removed:
154 | raise DomainDoesNotExist(f"{domain} does not exist")
155 |
156 | template["apps"]["http"]["servers"][f"{port}"]["routes"] = routes
157 | return template
158 |
159 | except KeyError:
160 | raise
161 | except IndexError:
162 | raise
163 |
164 |
165 | def list_domains(template, port=HTTPS_PORT):
166 | try:
167 | domains = []
168 |
169 | routes = template["apps"]["http"]["servers"][f"{port}"]["routes"]
170 | for route in routes:
171 | for match in route.get("match", []):
172 | for host in match.get("host", []):
173 | domains.append(host)
174 |
175 | return domains
176 | except KeyError:
177 | return []
178 | except IndexError:
179 | return []
180 |
--------------------------------------------------------------------------------
/app/main.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 |
4 | from dotenv import load_dotenv
5 | from fastapi import FastAPI, Depends
6 | from fastapi.openapi.docs import get_swagger_ui_html
7 | from fastapi.openapi.models import APIKey
8 | from fastapi.openapi.utils import get_openapi
9 | from starlette.middleware.cors import CORSMiddleware
10 | from starlette.middleware.trustedhost import TrustedHostMiddleware
11 | from starlette.responses import RedirectResponse, JSONResponse
12 |
13 | from app.api import domain_api
14 | from app.security import API_KEY_NAME, COOKIE_DOMAIN, get_api_key
15 |
16 | # Load all environment variables from .env uploaded_file
17 | load_dotenv()
18 | logger = logging.getLogger(__name__)
19 |
20 | app = FastAPI()
21 | app.include_router(domain_api)
22 |
23 | # CORS support
24 | ALLOWED_ORIGINS = os.environ.get('ALLOWED_ORIGINS', '*')
25 | ALLOWED_METHODS = os.environ.get('ALLOWED_METHODS', '*')
26 | ALLOWED_HEADERS = os.environ.get('ALLOWED_HEADERS', '*')
27 |
28 | app.add_middleware(
29 | CORSMiddleware,
30 | allow_origins=ALLOWED_ORIGINS,
31 | allow_credentials=True,
32 | allow_methods=ALLOWED_METHODS,
33 | allow_headers=ALLOWED_HEADERS,
34 | )
35 |
36 | # Trusted Hosts
37 | trusted_hosts = os.environ.get('TRUSTED_HOSTS', None)
38 | if trusted_hosts:
39 | trusted_hosts = [host.strip() for host in trusted_hosts.split(",")]
40 | app.add_middleware(TrustedHostMiddleware, allowed_hosts=trusted_hosts)
41 |
42 |
43 | @app.get("/logout", tags=["default"])
44 | async def logout_and_remove_cookie():
45 | response = RedirectResponse(url="/")
46 | response.delete_cookie(API_KEY_NAME, domain=COOKIE_DOMAIN)
47 | return response
48 |
49 |
50 | @app.get("/openapi.json", tags=["default"])
51 | async def get_open_api_endpoint(api_key: APIKey = Depends(get_api_key)):
52 | response = JSONResponse(
53 | get_openapi(title="SaaS HTTPS API", version='1.0.0', routes=app.routes)
54 | )
55 | return response
56 |
57 |
58 | @app.get("/docs", tags=["default"])
59 | async def get_documentation(api_key: APIKey = Depends(get_api_key)):
60 | response = get_swagger_ui_html(openapi_url="/openapi.json", title="docs")
61 | response.set_cookie(
62 | API_KEY_NAME,
63 | value=api_key,
64 | domain=COOKIE_DOMAIN,
65 | httponly=True,
66 | max_age=1800,
67 | expires=1800,
68 | )
69 | return response
70 |
71 |
72 | @app.on_event("startup")
73 | async def startup():
74 | logger.info("App started")
75 |
76 |
77 | @app.on_event("shutdown")
78 | async def shutdown():
79 | logger.info("App is shutting down")
80 |
--------------------------------------------------------------------------------
/app/security.py:
--------------------------------------------------------------------------------
1 | import os
2 | import uuid
3 |
4 | from fastapi import Security, HTTPException
5 | from fastapi.security.api_key import APIKeyQuery, APIKeyCookie, APIKeyHeader
6 | from starlette.status import HTTP_403_FORBIDDEN
7 |
8 | API_KEY = os.environ.get('API_KEY', str(uuid.uuid4()))
9 | API_KEY_NAME = os.environ.get('API_KEY_NAME', 'api_key')
10 | COOKIE_DOMAIN = os.environ.get('CADDY_MAIN_DOMAIN_HOST', 'localtest.me')
11 |
12 | api_key_query = APIKeyQuery(name=API_KEY_NAME, auto_error=False)
13 | api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
14 | api_key_cookie = APIKeyCookie(name=API_KEY_NAME, auto_error=False)
15 |
16 |
17 | async def get_api_key(
18 | api_key_query: str = Security(api_key_query),
19 | api_key_header: str = Security(api_key_header),
20 | api_key_cookie: str = Security(api_key_cookie),
21 | ):
22 |
23 | if api_key_query == API_KEY:
24 | return api_key_query
25 | elif api_key_header == API_KEY:
26 | return api_key_header
27 | elif api_key_cookie == API_KEY:
28 | return api_key_cookie
29 | else:
30 | raise HTTPException(
31 | status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
32 | )
33 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3.7"
2 |
3 | services:
4 | https:
5 | image: sireto/custom-domain:latest
6 | ports:
7 | - "80:80"
8 | - "443:443"
9 | - "443:443/udp"
10 | - "9000:9000"
11 | restart: unless-stopped
12 | networks:
13 | - frontend
14 | env_file:
15 | - .env
16 | volumes:
17 | - https_domains:/app/domains
18 | - https_data:/root/.local/share
19 |
20 | volumes:
21 | https_data:
22 | external: true
23 | https_domains:
24 | external: true
25 |
26 | networks:
27 | frontend:
--------------------------------------------------------------------------------
/domains/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sireto/custom-domain/99220f0effac0541c140a6395aba1ffe18c54fa0/domains/.gitignore
--------------------------------------------------------------------------------
/entrypoint.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | /usr/bin/caddy start
4 | /usr/local/bin/uvicorn app.main:app --host 0.0.0.0 --port 9000
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import uvicorn
2 |
3 | if __name__ == "__main__":
4 | uvicorn.run("app.main:app", host="0.0.0.0", port=8000, log_level="info")
5 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi[all]
2 | uvicorn[standard]
3 | python-dotenv
4 | httpx
5 | requests
6 | validators
--------------------------------------------------------------------------------