diff --git a/integrations/rapid7-insightidr/manifest.yaml b/integrations/rapid7-insightidr/manifest.yaml index e137394..0c841d0 100644 --- a/integrations/rapid7-insightidr/manifest.yaml +++ b/integrations/rapid7-insightidr/manifest.yaml @@ -1,8 +1,8 @@ id: rapid7_insightidr name: Rapid7 InsightIDR -version: 1.0.0 +version: 1.1.0 description: "Rapid7 InsightIDR (REST API) — investigation ingestion and full lifecycle (list/get/search/create/update/assign/set-status/bulk-close), investigation alerts and Rapid7 product alerts, custom threat indicators (add/replace), log management and LEQL log/log-set queries with downloads, and user directory search." -changelog: "1.0.0 — Initial release: investigation ingestion (list_investigations) with an exhaustive OCSF mapper, 18 commands across investigations, alerts, custom threats, logs/LEQL search and users. API v1/v2 selectable per instance and per command." +changelog: "1.1.0 — Add the Alert Triage API (/idr/at): search alerts, get an alert, its evidence, its actors and its process trees, plus the tenant's alert field catalogue. These carry the detection content the investigation endpoints do not — MITRE T-codes, matched rule keys, assets and accounts, command lines. MDR-gated. | 1.0.0 — Initial release: investigation ingestion (list_investigations) with an exhaustive OCSF mapper, 18 commands across investigations, alerts, custom threats, logs/LEQL search and users. API v1/v2 selectable per instance and per command." category: siem # Per-instance configuration. The Insight platform region selects the API host @@ -315,6 +315,104 @@ commands: required: [] outputs_schema: { properties: {} } + + # ── Alert Triage API (/idr/at) ────────────────────────────────────────────── + # A separate API from the investigation endpoints, and the only place the + # actual detection content lives: an investigation and its /alerts list carry + # metadata (title, priority, rule name) and no evidence at all. Access is + # restricted to Managed Detection and Response customers with the Alerts + # experience — a key that works everywhere else can still be refused here, + # which the commands report as a named 401/403 rather than an empty result. + - id: search_alerts + name: rapid7-insight-idr-search-alerts + description: "Search alerts over a time window (Alert Triage API). Returns full alert details — detection rule with its MITRE T-codes, priority, status, disposition, Rapid7's AI-suggested disposition, the parent investigation RRN and the log entries behind it. Results path = alerts; use field_ids to pull the per-tenant fields (hostnames, accounts, command lines) that are otherwise absent." + risk: read + inputs_schema: + properties: + start_time: { type: string, description: "ISO-8601 start of the search window (required by the API; defaults to default_days ago). Incremental fetch watermark." } + end_time: { type: string, description: "ISO-8601 end of the search window" } + default_days: { type: string, description: "Window size in days used when start_time is absent (default 1)" } + leql: { type: string, description: "LEQL WHERE clause to match against" } + field_ids: { type: string, description: "Comma-separated additional field ids to include on each alert (see rapid7-insight-idr-list-alert-fields). Empty means no additional fields are returned." } + search_field: { type: string, description: "Comma-separated field ids for a single search term" } + search_values: { type: string, description: "Comma-separated values the search_field must match (OR'ed together)" } + search_operator: { type: string, description: "EQUALS, NOT_EQUALS, CONTAINS, GREATER_THAN or LESS_THAN (default EQUALS)" } + terms_json: { type: string, description: "Raw JSON array of search terms, for criteria the simple triple cannot express. Takes precedence over search_field/search_values." } + sort_field: { type: string, description: "Field id to sort on" } + sort_direction: { type: string, description: "ASC or DESC (default ASC)" } + rrns_only: { type: string, description: "Return only alert RRNs instead of full details (true/false)" } + index: { type: string, description: "0-based page index to start from" } + page_size: { type: string, description: "Page size" } + limit: { type: number, description: "Maximum number of alerts to retrieve (default 50)" } + required: [] + outputs_schema: { properties: {} } + + - id: get_alert + name: rapid7-insight-idr-get-alert + description: "Retrieve a single alert by its RRN (Alert Triage API), optionally with additional fields." + risk: read + inputs_schema: + properties: + alert_rrn: { type: string, description: "Alert RRN (rrn:alerts:::alert:...)" } + field_ids: { type: string, description: "Comma-separated additional field ids to include" } + required: [alert_rrn] + outputs_schema: { properties: {} } + + - id: get_alert_evidence + name: rapid7-insight-idr-get-alert-evidence + description: "Retrieve the evidence behind a single alert (Alert Triage API): the events that triggered it, the keys and values the rule matched on, and the log entries they came from." + risk: read + inputs_schema: + properties: + alert_rrn: { type: string, description: "Alert RRN" } + index: { type: string, description: "0-based page index" } + page_size: { type: string, description: "Page size" } + limit: { type: number, description: "Maximum number of evidence items (default 50)" } + required: [alert_rrn] + outputs_schema: { properties: {} } + + - id: get_alert_actors + name: rapid7-insight-idr-get-alert-actors + description: "Retrieve an alert's actors (Alert Triage API): the assets, accounts and IP addresses involved, each with its display name. This is where an alert's observables come from — nothing in the investigation endpoints carries them." + risk: read + inputs_schema: + properties: + alert_rrn: { type: string, description: "Alert RRN" } + index: { type: string, description: "0-based page index" } + page_size: { type: string, description: "Page size" } + limit: { type: number, description: "Maximum number of actors (default 50)" } + required: [alert_rrn] + outputs_schema: { properties: {} } + + - id: get_alert_process_trees + name: rapid7-insight-idr-get-alert-process-trees + description: "Retrieve all process trees for an alert (Alert Triage API): process name, PID, command line, executing user and file hashes, with child processes nested." + risk: read + inputs_schema: + properties: + alert_rrn: { type: string, description: "Alert RRN" } + force_refresh: { type: string, description: "Regenerate the tree instead of returning the cached one (true/false). Documented as expensive and slow — leave off unless the cached tree is stale." } + branch: { type: string, description: "Branch number to generate the process tree with" } + index: { type: string, description: "0-based page index" } + page_size: { type: string, description: "Page size" } + limit: { type: number, description: "Maximum number of trees (default 10)" } + required: [alert_rrn] + outputs_schema: { properties: {} } + + - id: list_alert_fields + name: rapid7-insight-idr-list-alert-fields + description: "List the alert fields supported by the tenant (Alert Triage API v2). Field ids are dotted paths (process.cmd_line, …) and are what search_alerts and get_alert accept in field_ids — run this first to learn which ones this tenant exposes." + risk: read + inputs_schema: + properties: + path: { type: string, description: "Limit results to fields at or below this node of the dotted hierarchy" } + path_depth: { type: string, description: "Depth to round results to, after path is applied" } + index: { type: string, description: "0-based page index" } + page_size: { type: string, description: "Page size (default 200)" } + limit: { type: number, description: "Maximum number of fields to retrieve" } + required: [] + outputs_schema: { properties: {} } + # ── Connectivity test ───────────────────────────────────────────────────── - id: test_connection name: rapid7-insight-idr-test-connection diff --git a/integrations/rapid7-insightidr/scripts/get_alert.py b/integrations/rapid7-insightidr/scripts/get_alert.py new file mode 100644 index 0000000..3513aa0 --- /dev/null +++ b/integrations/rapid7-insightidr/scripts/get_alert.py @@ -0,0 +1,65 @@ +import json, os, sys, urllib.request, urllib.parse, urllib.error + +# The Alert Triage API lives under /idr/at, a base of its own — not /idr/v1 or +# /idr/v2 like the investigation endpoints. Same host, same API key. +AT = "idr/at/" + + +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"} + multi = str(s.get("is_multi_customer") or "").strip().lower() in ("1", "true", "yes") + return base, headers, multi + + +def _inputs(): + return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) + + +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, params=None, body=None): + base, headers, _ = _cfg() + url = base + path.lstrip("/") + if params: + clean = {k: v for k, v in params.items() if v not in (None, "")} + if clean: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean, doseq=True) + data = json.dumps(body).encode("utf-8") if body is not None else None + req = urllib.request.Request(url, 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() + rrn = inp.get("alert_rrn", "") + params = {} + ids = _list(inp.get("field_ids")) + if ids: + params["field_ids"] = ids + print(json.dumps(request("GET", AT + "alerts/" + urllib.parse.quote(rrn, safe=""), params=params))) + + +try: + run() +except urllib.error.HTTPError as e: + detail = e.read().decode("utf-8", "replace") + if e.code in (401, 403): + detail += (" — the Alert Triage API (/idr/at) is only available to Managed Detection and" + " Response customers with access to the Alerts experience; a key that works on" + " the investigation endpoints can still be refused here") + print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail})) + sys.exit(1) +except Exception as e: + print(json.dumps({"error": str(e)})) + sys.exit(1) diff --git a/integrations/rapid7-insightidr/scripts/get_alert_actors.py b/integrations/rapid7-insightidr/scripts/get_alert_actors.py new file mode 100644 index 0000000..c38b98b --- /dev/null +++ b/integrations/rapid7-insightidr/scripts/get_alert_actors.py @@ -0,0 +1,65 @@ +import json, os, sys, urllib.request, urllib.parse, urllib.error + +# The Alert Triage API lives under /idr/at, a base of its own — not /idr/v1 or +# /idr/v2 like the investigation endpoints. Same host, same API key. +AT = "idr/at/" + + +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"} + multi = str(s.get("is_multi_customer") or "").strip().lower() in ("1", "true", "yes") + return base, headers, multi + + +def _inputs(): + return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) + + +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, params=None, body=None): + base, headers, _ = _cfg() + url = base + path.lstrip("/") + if params: + clean = {k: v for k, v in params.items() if v not in (None, "")} + if clean: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean, doseq=True) + data = json.dumps(body).encode("utf-8") if body is not None else None + req = urllib.request.Request(url, 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() + rrn = inp.get("alert_rrn", "") + limit = int(inp.get("limit") or 50) + out = request("GET", AT + "alerts/" + urllib.parse.quote(rrn, safe="") + "/actors", + params={"index": inp.get("index") or "0", "size": inp.get("page_size") or limit}) + actors = out.get("actors") or [] + print(json.dumps({"rrn": rrn, "actors": actors[:limit], "metadata": out.get("metadata") or {}})) + + +try: + run() +except urllib.error.HTTPError as e: + detail = e.read().decode("utf-8", "replace") + if e.code in (401, 403): + detail += (" — the Alert Triage API (/idr/at) is only available to Managed Detection and" + " Response customers with access to the Alerts experience; a key that works on" + " the investigation endpoints can still be refused here") + print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail})) + sys.exit(1) +except Exception as e: + print(json.dumps({"error": str(e)})) + sys.exit(1) diff --git a/integrations/rapid7-insightidr/scripts/get_alert_evidence.py b/integrations/rapid7-insightidr/scripts/get_alert_evidence.py new file mode 100644 index 0000000..119a4ac --- /dev/null +++ b/integrations/rapid7-insightidr/scripts/get_alert_evidence.py @@ -0,0 +1,65 @@ +import json, os, sys, urllib.request, urllib.parse, urllib.error + +# The Alert Triage API lives under /idr/at, a base of its own — not /idr/v1 or +# /idr/v2 like the investigation endpoints. Same host, same API key. +AT = "idr/at/" + + +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"} + multi = str(s.get("is_multi_customer") or "").strip().lower() in ("1", "true", "yes") + return base, headers, multi + + +def _inputs(): + return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) + + +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, params=None, body=None): + base, headers, _ = _cfg() + url = base + path.lstrip("/") + if params: + clean = {k: v for k, v in params.items() if v not in (None, "")} + if clean: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean, doseq=True) + data = json.dumps(body).encode("utf-8") if body is not None else None + req = urllib.request.Request(url, 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() + rrn = inp.get("alert_rrn", "") + limit = int(inp.get("limit") or 50) + out = request("GET", AT + "alerts/" + urllib.parse.quote(rrn, safe="") + "/evidences", + params={"index": inp.get("index") or "0", "size": inp.get("page_size") or limit}) + evidences = out.get("evidences") or [] + print(json.dumps({"rrn": rrn, "evidences": evidences[:limit], "metadata": out.get("metadata") or {}})) + + +try: + run() +except urllib.error.HTTPError as e: + detail = e.read().decode("utf-8", "replace") + if e.code in (401, 403): + detail += (" — the Alert Triage API (/idr/at) is only available to Managed Detection and" + " Response customers with access to the Alerts experience; a key that works on" + " the investigation endpoints can still be refused here") + print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail})) + sys.exit(1) +except Exception as e: + print(json.dumps({"error": str(e)})) + sys.exit(1) diff --git a/integrations/rapid7-insightidr/scripts/get_alert_process_trees.py b/integrations/rapid7-insightidr/scripts/get_alert_process_trees.py new file mode 100644 index 0000000..797a1e3 --- /dev/null +++ b/integrations/rapid7-insightidr/scripts/get_alert_process_trees.py @@ -0,0 +1,73 @@ +import json, os, sys, urllib.request, urllib.parse, urllib.error + +# The Alert Triage API lives under /idr/at, a base of its own — not /idr/v1 or +# /idr/v2 like the investigation endpoints. Same host, same API key. +AT = "idr/at/" + + +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"} + multi = str(s.get("is_multi_customer") or "").strip().lower() in ("1", "true", "yes") + return base, headers, multi + + +def _inputs(): + return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) + + +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, params=None, body=None): + base, headers, _ = _cfg() + url = base + path.lstrip("/") + if params: + clean = {k: v for k, v in params.items() if v not in (None, "")} + if clean: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean, doseq=True) + data = json.dumps(body).encode("utf-8") if body is not None else None + req = urllib.request.Request(url, 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() + rrn = inp.get("alert_rrn", "") + limit = int(inp.get("limit") or 10) + # force_refresh is left off by default on purpose: the API documents + # regeneration as expensive and slow, and the command runs under the + # server's 90-second budget like every other one. + params = {"index": inp.get("index") or "0", "size": inp.get("page_size") or limit} + if str(inp.get("force_refresh") or "").strip().lower() in ("1", "true", "yes"): + params["force_refresh"] = "true" + if inp.get("branch") not in (None, ""): + params["branch"] = inp["branch"] + out = request("POST", AT + "alerts/" + urllib.parse.quote(rrn, safe="") + "/process_trees/latest", + params=params) + trees = out.get("process_trees") or [] + print(json.dumps({"rrn": rrn, "process_trees": trees[:limit], "metadata": out.get("metadata") or {}})) + + +try: + run() +except urllib.error.HTTPError as e: + detail = e.read().decode("utf-8", "replace") + if e.code in (401, 403): + detail += (" — the Alert Triage API (/idr/at) is only available to Managed Detection and" + " Response customers with access to the Alerts experience; a key that works on" + " the investigation endpoints can still be refused here") + print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail})) + sys.exit(1) +except Exception as e: + print(json.dumps({"error": str(e)})) + sys.exit(1) diff --git a/integrations/rapid7-insightidr/scripts/list_alert_fields.py b/integrations/rapid7-insightidr/scripts/list_alert_fields.py new file mode 100644 index 0000000..7c85cd8 --- /dev/null +++ b/integrations/rapid7-insightidr/scripts/list_alert_fields.py @@ -0,0 +1,69 @@ +import json, os, sys, urllib.request, urllib.parse, urllib.error + +# The Alert Triage API lives under /idr/at, a base of its own — not /idr/v1 or +# /idr/v2 like the investigation endpoints. Same host, same API key. +AT = "idr/at/" + + +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"} + multi = str(s.get("is_multi_customer") or "").strip().lower() in ("1", "true", "yes") + return base, headers, multi + + +def _inputs(): + return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) + + +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, params=None, body=None): + base, headers, _ = _cfg() + url = base + path.lstrip("/") + if params: + clean = {k: v for k, v in params.items() if v not in (None, "")} + if clean: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean, doseq=True) + data = json.dumps(body).encode("utf-8") if body is not None else None + req = urllib.request.Request(url, 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() + # /alerts/fields is deprecated in favour of /alerts/2/fields. Field ids are + # dotted paths (process.cmd_line, …) and are what search_alerts and + # get_alert accept in field_ids — this command is how you discover them. + out = request("GET", AT + "alerts/2/fields", params={ + "path": inp.get("path"), + "path_depth": inp.get("path_depth"), + "index": inp.get("index") or "0", + "size": inp.get("page_size") or inp.get("limit") or 200, + }) + print(json.dumps(out)) + + +try: + run() +except urllib.error.HTTPError as e: + detail = e.read().decode("utf-8", "replace") + if e.code in (401, 403): + detail += (" — the Alert Triage API (/idr/at) is only available to Managed Detection and" + " Response customers with access to the Alerts experience; a key that works on" + " the investigation endpoints can still be refused here") + print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail})) + sys.exit(1) +except Exception as e: + print(json.dumps({"error": str(e)})) + sys.exit(1) diff --git a/integrations/rapid7-insightidr/scripts/search_alerts.py b/integrations/rapid7-insightidr/scripts/search_alerts.py new file mode 100644 index 0000000..9ef5bde --- /dev/null +++ b/integrations/rapid7-insightidr/scripts/search_alerts.py @@ -0,0 +1,135 @@ +import json, os, sys, urllib.request, urllib.parse, urllib.error + +# The Alert Triage API lives under /idr/at, a base of its own — not /idr/v1 or +# /idr/v2 like the investigation endpoints. Same host, same API key. +AT = "idr/at/" + + +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"} + multi = str(s.get("is_multi_customer") or "").strip().lower() in ("1", "true", "yes") + return base, headers, multi + + +def _inputs(): + return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) + + +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, params=None, body=None): + base, headers, _ = _cfg() + url = base + path.lstrip("/") + if params: + clean = {k: v for k, v in params.items() if v not in (None, "")} + if clean: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean, doseq=True) + data = json.dumps(body).encode("utf-8") if body is not None else None + req = urllib.request.Request(url, 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 {} + +from datetime import datetime, timedelta, timezone + +ISO = "%Y-%m-%dT%H:%M:%SZ" +PAGE = 100 + + +def _terms(inp): + """Build the search terms array. + + Two ways in, because the field ids are per-tenant and discovered at runtime + (see list_alert_fields): a raw JSON passthrough for full control, and one + field/operator/values triple for the common case. + """ + raw = inp.get("terms_json") + if raw: + parsed = json.loads(raw) if isinstance(raw, str) else raw + return parsed if isinstance(parsed, list) else [parsed] + field_ids = _list(inp.get("search_field")) + values = _list(inp.get("search_values")) + if not field_ids or not values: + # The schema marks terms as required. An empty array is what "no filter" + # has to look like; if the tenant refuses it, the HTTP error says so + # rather than this script inventing a filter nobody asked for. + return [] + op = str(inp.get("search_operator") or "EQUALS").strip().upper() + return [{"field_ids": field_ids, "operator": op, "terms": values}] + + +def run(): + inp = _inputs() + limit = int(inp.get("limit") or 50) + start_time = inp.get("start_time") + end_time = inp.get("end_time") + if not start_time: + # start_time is required by the API. Default to a window rather than + # failing: an ingestion rule that has never run has no watermark yet. + days = int(inp.get("default_days") or 1) + start_time = (datetime.now(timezone.utc) - timedelta(days=days)).strftime(ISO) + search = {"start_time": start_time, "terms": _terms(inp)} + if end_time: + search["end_time"] = end_time + if inp.get("leql"): + search["leql"] = inp["leql"] + + body = {"search": search} + ids = _list(inp.get("field_ids")) + if ids: + # Without field_ids the alert carries no additional fields at all — this + # is where the hostnames, accounts and command lines come from. + body["field_ids"] = ids + sort_field = inp.get("sort_field") + if sort_field: + body["sorts"] = [{"field_id": sort_field, + "order": str(inp.get("sort_direction") or "ASC").strip().upper()}] + + rrns_only = str(inp.get("rrns_only") or "").strip().lower() in ("1", "true", "yes") + alerts, rrns, meta = [], [], {} + index = int(inp.get("index") or 0) + while len(alerts) + len(rrns) < limit: + size = min(PAGE, limit - len(alerts) - len(rrns)) + out = request("POST", AT + "alerts/ops/search", + params={"index": index, "size": size, + "rrns_only": "true" if rrns_only else None}, + body=body) + meta = out.get("metadata") or {} + page_alerts = out.get("alerts") or [] + page_rrns = out.get("rrns") or [] + alerts.extend(page_alerts) + rrns.extend(page_rrns) + if meta.get("is_last_index") or not (page_alerts or page_rrns): + break + index += 1 + + result = {"metadata": meta} + if rrns_only: + result["rrns"] = rrns[:limit] + else: + result["alerts"] = alerts[:limit] + print(json.dumps(result)) + + +try: + run() +except urllib.error.HTTPError as e: + detail = e.read().decode("utf-8", "replace") + if e.code in (401, 403): + detail += (" — the Alert Triage API (/idr/at) is only available to Managed Detection and" + " Response customers with access to the Alerts experience; a key that works on" + " the investigation endpoints can still be refused here") + print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail})) + sys.exit(1) +except Exception as e: + print(json.dumps({"error": str(e)})) + sys.exit(1)