| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import base64
- import hashlib
- import hmac
- import os
- from pathlib import Path
- import ssl
- import sys
- import time
- from urllib.parse import urlsplit
- from urllib.request import Request, HTTPSHandler, HTTPRedirectHandler, ProxyHandler, build_opener
- from urllib.error import HTTPError
- from uuid import UUID, uuid4
- config = dict(line.split("=", 1) for line in Path("client.env").read_text(encoding="utf-8").splitlines())
- base = os.environ.get("INGRESS_BASE", config["INGRESS_BASE"]).rstrip("/")
- origin = urlsplit(base)
- if origin.scheme != "https" or not origin.hostname or origin.username or origin.password or origin.path or origin.query or origin.fragment:
- sys.exit("INGRESS_BASE must be an HTTPS origin")
- if len(sys.argv) != 3 or sys.argv[1] not in ("send", "status"):
- sys.exit("Usage: push.py send <file> | status <batchId>")
- sending = sys.argv[1] == "send"
- endpoint = config["DATASET_ENDPOINT"]
- method, body, content_type, idem, schema = "GET", b"", "", "", ""
- if sending:
- method, body = "POST", Path(sys.argv[2]).read_bytes()
- content_type = "application/x-ndjson" if sys.argv[2].lower().endswith(".ndjson") else "application/json"
- idem, schema = os.environ["IDEMPOTENCY_KEY"], config["SCHEMA_VERSION"]
- else:
- endpoint += "/batches/" + str(UUID(sys.argv[2]))
- key = os.environ["ACCESS_KEY"]
- factory = "" if content_type == "application/json" else config["FACTORY_ID"]
- version = "mdp-ingress-hmac-sha256-v2"
- timestamp, nonce = str(int(time.time())), uuid4().hex
- digest = hashlib.sha256(body).hexdigest()
- canonical = "&".join((version, method, endpoint, key, timestamp, nonce, digest, idem, content_type, factory, schema))
- signature = base64.b64encode(hmac.digest(base64.b64decode(os.environ["SIGNING_KEY_BASE64"]), canonical.encode(), "sha256")).decode()
- headers = {"X-Access-Key": key, "X-Timestamp": timestamp, "X-Nonce": nonce, "X-Content-SHA256": digest,
- "X-Signature": signature, "X-Signature-Version": version}
- if factory:
- headers["X-Factory-Id"] = factory
- if sending:
- headers.update({"Content-Type": content_type, "Idempotency-Key": idem, "X-Schema-Version": schema})
- class NoRedirect(HTTPRedirectHandler):
- def redirect_request(self, *args, **kwargs):
- return None
- context = ssl.create_default_context(cafile=os.environ.get("INGRESS_CA_FILE"))
- opener = build_opener(ProxyHandler({}), HTTPSHandler(context=context), NoRedirect())
- try:
- with opener.open(Request(base + endpoint, data=body if sending else None, headers=headers, method=method), timeout=30) as response:
- print(f"HTTP {response.status}")
- print(response.read().decode())
- except HTTPError as error:
- print(f"HTTP {error.code}")
- if error.headers.get("Retry-After"):
- print("Retry-After:", error.headers["Retry-After"])
- print(error.read().decode())
- sys.exit(1)
|