84 lines
2.8 KiB
Python
84 lines
2.8 KiB
Python
#!/usr/bin/env python3
|
|
import argparse
|
|
import ipaddress
|
|
import json
|
|
import pathlib
|
|
import socket
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
|
|
class NoRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
|
|
|
|
def validate_base_url(raw_url):
|
|
parsed = urllib.parse.urlsplit(raw_url)
|
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
|
raise ValueError("Base URL must use http or https and include a host.")
|
|
if parsed.username or parsed.password or parsed.query or parsed.fragment:
|
|
raise ValueError("Credentials, query strings, and fragments are forbidden.")
|
|
if parsed.path not in {"", "/"}:
|
|
raise ValueError("Base URL must not include an API path.")
|
|
if parsed.hostname == "localhost":
|
|
addresses = [ipaddress.ip_address("127.0.0.1")]
|
|
else:
|
|
addresses = [
|
|
ipaddress.ip_address(item[4][0])
|
|
for item in socket.getaddrinfo(
|
|
parsed.hostname, parsed.port, type=socket.SOCK_STREAM
|
|
)
|
|
]
|
|
if not addresses or any(
|
|
not (address.is_loopback or address.is_private or address.is_link_local)
|
|
for address in addresses
|
|
):
|
|
raise ValueError("Refusing to send a bearer token to a non-local host.")
|
|
return raw_url.rstrip("/")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Close a local benchmark session.")
|
|
parser.add_argument("--base-url", default="http://127.0.0.1:3001")
|
|
parser.add_argument("--headers-file", required=True)
|
|
parser.add_argument("--timeout", type=float, default=5.0)
|
|
args = parser.parse_args()
|
|
|
|
try:
|
|
base_url = validate_base_url(args.base_url)
|
|
headers = json.loads(
|
|
pathlib.Path(args.headers_file).read_text(encoding="utf-8")
|
|
)
|
|
if not isinstance(headers, dict) or not isinstance(
|
|
headers.get("Authorization"), str
|
|
):
|
|
raise ValueError("Temporary headers file is invalid.")
|
|
opener = urllib.request.build_opener(
|
|
urllib.request.ProxyHandler({}), NoRedirectHandler()
|
|
)
|
|
request = urllib.request.Request(
|
|
base_url + "/api/auth/logout",
|
|
data=b"{}",
|
|
headers=headers,
|
|
method="POST",
|
|
)
|
|
with opener.open(request, timeout=args.timeout) as response:
|
|
response.read(1024)
|
|
if not 200 <= response.status < 300:
|
|
raise RuntimeError(f"Logout returned HTTP {response.status}.")
|
|
except (
|
|
OSError,
|
|
ValueError,
|
|
RuntimeError,
|
|
json.JSONDecodeError,
|
|
socket.gaierror,
|
|
urllib.error.URLError,
|
|
) as exc:
|
|
raise SystemExit(str(exc)) from exc
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|