import json, os, sys, urllib.request, urllib.parse, urllib.error def _cfg(): s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}")) region = str(s.get("region") or "us").strip().lower() base = "https://" + region + ".api.insight.rapid7.com/" headers = {"X-Api-Key": s.get("api_key", ""), "Content-Type": "application/json", "Accept": "application/json"} return base, headers def _inputs(): return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) def _prune(d): return {k: v for k, v in d.items() if v not in (None, "", {}, [])} def _list(v): if v in (None, ""): return [] if isinstance(v, list): return [str(x).strip() for x in v if str(x).strip()] return [p.strip() for p in str(v).split(",") if p.strip()] def request(method, path, body=None): base, headers = _cfg() data = json.dumps(body).encode("utf-8") if body is not None else None req = urllib.request.Request(base + path.lstrip("/"), data=data, headers=headers, method=method) with urllib.request.urlopen(req, timeout=90) as r: raw = r.read() return json.loads(raw) if raw else {} def run(): inp = _inputs() # The Comments API addresses its target by RRN only. The short investigation ID # the v1 endpoints accept is rejected here, and the API answers 400 without # naming the parameter — so refuse it up front with the reason. target = str(inp.get("investigation_id") or "").strip() if not target: raise ValueError("investigation_id is required: the RRN of the investigation to comment on") if not target.startswith("rrn:"): raise ValueError( "investigation_id must be an RRN (rrn:investigation:::investigation:), " "not the short investigation ID: the Comments API targets a resource by RRN. Got " + repr(target) ) comment = inp.get("comment") attachments = _list(inp.get("attachments")) if comment in (None, "") and not attachments: raise ValueError("comment is required (or attachments, to post a comment carrying only files)") body = _prune({ "target": target, "body": comment, "attachments": attachments, }) print(json.dumps(request("POST", "idr/v1/comments", body=body))) try: run() 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)