blob: f65122af9f487915fb313a7c5c0fae7d3577f537 [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
14def parse_auth(authorization):
15 auth_type, auth_info = authorization.split(" ", maxsplit=1)
16 if auth_type != "Basic":
17 raise ValueError(f"Unknown auth type: {auth_type}")
18 username, _ = base64.b64decode(auth_info).decode().split(":", 1)
19 return username
20
21class Server(BaseHTTPRequestHandler):
22 def _set_response(self):
23 self.send_response(200)
24 self.send_header("Content-type", "text/html")
25 self.end_headers()
26
27 def _write(self, text):
28 self.wfile.write(text.encode("utf-8"))
29
30 def do_GET(self):
31 self._set_response()
32 self._write(f"GET request for {self.path}")
33 self._write("<br/>")
34 username = parse_auth(self.headers["Authorization"])
35 self._write(f"Hello, {username}")
36
37def main():
38 port = int(os.environ["APACHE_WRAPPED_PORT"])
39 server_address = ("", port)
40 httpd = HTTPServer(server_address, Server)
41 try:
42 httpd.serve_forever()
43 except KeyboardInterrupt:
44 pass
45 httpd.server_close()
46
47if __name__ == "__main__":
48 main()