import json, os, sys, time, urllib.request, urllib.parse, urllib.error SEVERITIES = ["low", "medium", "high", "critical"] RETRIES = 3 def retryable(method, status): # HarfangLab answers a 500 now and then on a call that passes when sent again. # A read is safe to resend; a write only on an answer that says the action was # not run (rate limit, gateway down), so an isolation or a job is never sent twice. if status in (429, 502, 503): return True return method == "GET" and status in (500, 504) def request(method, url, headers): for attempt in range(RETRIES + 1): req = urllib.request.Request(url, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=90) as resp: raw = resp.read() return json.loads(raw) if raw else {} except urllib.error.HTTPError as e: if attempt == RETRIES or not retryable(method, e.code): raise e.close() time.sleep(2 ** attempt) def qs(params): clean = {} for k, v in params.items(): if v is None or v == "" or v == []: continue clean[k] = v return ("?" + urllib.parse.urlencode(clean)) if clean else "" def main(): secrets = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}")) inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) base = secrets.get("url", "").rstrip("/") headers = { "Authorization": "Token " + secrets.get("api_token", ""), "Accept": "application/json", "Content-Type": "application/json", } min_sev = str(inputs.get("min_severity") or "low").lower() level = ",".join(SEVERITIES[SEVERITIES.index(min_sev):]) if min_sev in SEVERITIES else ",".join(SEVERITIES) params = { "ordering": "-alert_time", "level": level, "limit": int(inputs.get("limit") or 100), "offset": 0, "status": inputs.get("status"), "alert_type": inputs.get("alert_type"), "alert_time__gte": inputs.get("created_after"), } url = base + "/api/data/alert/alert/Alert/" + qs(params) out = request("GET", url, headers) # The list endpoints echo the catalogue of filterable fields (~50 KB) on # every call; it says nothing about the results, so it is not passed on. out.pop("filters", None) print(json.dumps(out)) try: main() except urllib.error.HTTPError as e: print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")})) sys.exit(1) except Exception as e: print(json.dumps({"error": str(e)})) sys.exit(1)