|
| 1 | +import json |
| 2 | +import re |
| 3 | +from http.server import BaseHTTPRequestHandler |
| 4 | +from urllib.error import HTTPError |
| 5 | +from urllib.error import URLError |
| 6 | +from urllib.parse import urlparse |
| 7 | +from urllib.request import Request |
| 8 | +from urllib.request import urlopen |
| 9 | + |
| 10 | +import click |
| 11 | + |
| 12 | + |
| 13 | +class KnowledgeBaseHandler(BaseHTTPRequestHandler): |
| 14 | + """HTTP request handler for serving knowledge bases and health checks.""" |
| 15 | + |
| 16 | + token: str = "" |
| 17 | + instance_name: str = "" |
| 18 | + backend_url: str = "" |
| 19 | + |
| 20 | + def do_GET(self): |
| 21 | + """Handle GET requests.""" |
| 22 | + path = urlparse(self.path).path |
| 23 | + |
| 24 | + # Match /knowledge_bases/{uuid} pattern |
| 25 | + match = re.match(r"^/kb/([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$", path) |
| 26 | + |
| 27 | + if match: |
| 28 | + public_id = match.group(1) |
| 29 | + self.handle_knowledge_base(public_id) |
| 30 | + elif path == "/health": |
| 31 | + self.handle_health() |
| 32 | + else: |
| 33 | + self.send_error(404, "Not Found") |
| 34 | + |
| 35 | + def handle_knowledge_base(self, public_id): |
| 36 | + """Fetch and return knowledge base data.""" |
| 37 | + url = f"{self.backend_url}/knowledge_bases/private/{public_id}" |
| 38 | + |
| 39 | + # Validate URL scheme for security |
| 40 | + parsed_url = urlparse(url) |
| 41 | + if parsed_url.scheme not in ("http", "https"): |
| 42 | + self.send_response(400) |
| 43 | + self.send_header("Content-Type", "application/json") |
| 44 | + self.end_headers() |
| 45 | + error_msg = json.dumps({"error": "Invalid URL scheme. Only HTTP and HTTPS are allowed."}) |
| 46 | + self.wfile.write(error_msg.encode("utf-8")) |
| 47 | + return |
| 48 | + |
| 49 | + headers = {"Authorization": f"Bearer {self.token}", "X-Tenant": self.instance_name, "Content-Type": "application/json"} |
| 50 | + |
| 51 | + req = Request(url, headers=headers) # noqa: S310 |
| 52 | + |
| 53 | + try: |
| 54 | + # URL scheme validated above - only HTTP/HTTPS allowed |
| 55 | + with urlopen(req, timeout=30) as response: # noqa: S310 |
| 56 | + data = response.read() |
| 57 | + self.send_response(200) |
| 58 | + self.send_header("Content-Type", "application/json") |
| 59 | + self.end_headers() |
| 60 | + self.wfile.write(data) |
| 61 | + except HTTPError as e: |
| 62 | + error_body = e.read() |
| 63 | + error_data = error_body.decode("utf-8") if error_body else '{"error": "HTTP Error"}' |
| 64 | + self.send_response(e.code) |
| 65 | + self.send_header("Content-Type", "application/json") |
| 66 | + self.end_headers() |
| 67 | + self.wfile.write(error_data.encode("utf-8")) |
| 68 | + except URLError as e: |
| 69 | + self.send_response(500) |
| 70 | + self.send_header("Content-Type", "application/json") |
| 71 | + self.end_headers() |
| 72 | + error_msg = json.dumps({"error": str(e)}) |
| 73 | + self.wfile.write(error_msg.encode("utf-8")) |
| 74 | + |
| 75 | + def handle_health(self): |
| 76 | + """Handle health check endpoint.""" |
| 77 | + self.send_response(200) |
| 78 | + self.send_header("Content-Type", "application/json") |
| 79 | + self.end_headers() |
| 80 | + self.wfile.write(json.dumps({"status": "ok"}).encode("utf-8")) |
| 81 | + |
| 82 | + def log_message(self, format, *args): |
| 83 | + """Override to use click.echo for logging.""" |
| 84 | + click.echo(f"{self.address_string()} - {format % args}") |
0 commit comments