blob: 0661a8adbffd4a3f0332be71d50aa9491a240d9a [file] [log] [blame]
Philipp Schraderd0e33a42022-01-22 21:55:15 -08001"""This is a dummy server to demonstrate the apache_wrapper() rule.
2
3Don't run this server on its own. Instead run the
4`//build_tests:apache_https_demo` binary.
5
6When you authenticate against Apache via LDAP, this server prints the username
7you authenticated with and the path from the GET request.
8"""
9
10import base64
11from http.server import BaseHTTPRequestHandler, HTTPServer
12import os
13
Ravago Jones5127ccc2022-07-31 16:32:45 -070014
Philipp Schraderd0e33a42022-01-22 21:55:15 -080015def parse_auth(authorization):
16 auth_type, auth_info = authorization.split(" ", maxsplit=1)
17 if auth_type != "Basic":
18 raise ValueError(f"Unknown auth type: {auth_type}")
19 username, _ = base64.b64decode(auth_info).decode().split(":", 1)
20 return username
21
Ravago Jones5127ccc2022-07-31 16:32:45 -070022
Philipp Schraderd0e33a42022-01-22 21:55:15 -080023class Server(BaseHTTPRequestHandler):
Ravago Jones5127ccc2022-07-31 16:32:45 -070024
Philipp Schraderd0e33a42022-01-22 21:55:15 -080025 def _set_response(self):
26 self.send_response(200)
27 self.send_header("Content-type", "text/html")
28 self.end_headers()
29
30 def _write(self, text):
31 self.wfile.write(text.encode("utf-8"))
32
33 def do_GET(self):
34 self._set_response()
35 self._write(f"GET request for {self.path}")
36 self._write("<br/>")
37 username = parse_auth(self.headers["Authorization"])
38 self._write(f"Hello, {username}")
39
Ravago Jones5127ccc2022-07-31 16:32:45 -070040
Philipp Schraderd0e33a42022-01-22 21:55:15 -080041def main():
42 port = int(os.environ["APACHE_WRAPPED_PORT"])
43 server_address = ("", port)
44 httpd = HTTPServer(server_address, Server)
45 try:
46 httpd.serve_forever()
47 except KeyboardInterrupt:
48 pass
49 httpd.server_close()
50
Ravago Jones5127ccc2022-07-31 16:32:45 -070051
Philipp Schraderd0e33a42022-01-22 21:55:15 -080052if __name__ == "__main__":
53 main()