summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'ansible/roles/certs/files/leforward.py')
-rwxr-xr-xansible/roles/certs/files/leforward.py68
1 files changed, 68 insertions, 0 deletions
diff --git a/ansible/roles/certs/files/leforward.py b/ansible/roles/certs/files/leforward.py
new file mode 100755
index 0000000..dccbac1
--- /dev/null
+++ b/ansible/roles/certs/files/leforward.py
@@ -0,0 +1,68 @@
1#!/usr/bin/env python3
2
3""" Run a single-purpose HTTP server.
4
5Server takes all GET requests and redirects them to a new host
6if the request URI starts with SUBPATH, otherwise returns 404.
7
8Requests are redirected to the URL provided by --baseurl. """
9
10import socketserver
11import http.server
12import argparse
13import sys
14
15
16CHALLENGE_HOST = None
17SUBPATH = "/.well-known/acme-challenge"
18
19
20class RedirectChallenges(http.server.BaseHTTPRequestHandler):
21 def do_GET(self):
22 if self.path.startswith(SUBPATH):
23 self.send_response(301)
24 self.send_header('Location', f"{CHALLENGE_HOST}{self.path}")
25 else:
26 self.send_response(404)
27
28 self.end_headers()
29
30
31class ReusableServer(socketserver.TCPServer):
32 """ Allow TCPServer to reuse host address.
33
34 Without setting 'allow_reuse_address', we can get stuck in
35 TIME_WAIT after being killed and the stale state stops a new
36 server from attaching to the port."""
37
38 allow_reuse_address = True
39
40
41if __name__ == "__main__":
42 parser = argparse.ArgumentParser(
43 description="Redirect all URIs with matching prefix to another host")
44 parser.add_argument(
45 '--baseurl',
46 dest='baseurl',
47 required=True,
48 help="Destination URL for all matching URIs on this server")
49
50 args = parser.parse_args()
51 CHALLENGE_HOST = args.baseurl
52
53 if not CHALLENGE_HOST.startswith("http"):
54 print("Redirect URL must be a full URL starting with http")
55 sys.exit(1)
56
57 # If user gave us a trailing slash URL, remove slash.
58 if CHALLENGE_HOST[-1] == "/":
59 CHALLENGE_HOST = CHALLENGE_HOST[:-1]
60
61 serverAddress = ('', 80)
62
63 # Note: if running remotely by an SSH command, you MUST launch with '-t':
64 # > ssh -t me@otherhost leforward.py --baseurl http://otherserver.com
65 # If you omit '-t' the listening server won't terminate when you kill the
66 # ssh session, which probably isn't what you want.
67 with ReusableServer(serverAddress, RedirectChallenges) as httpd:
68 httpd.serve_forever()
Powered by cgit v1.2.3 (git 2.41.0)