import json, os, sys, ssl, http.cookiejar import urllib.parse, urllib.request, urllib.error def _cfg(): return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}")) def _inputs(): return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) def _ctx(cfg): if cfg.get("insecure"): c = ssl.create_default_context() c.check_hostname = False c.verify_mode = ssl.CERT_NONE return c return None class Client: def __init__(self, cfg): self.cfg = cfg self.base = str(cfg.get("base_url", "")).rstrip("/") + "/BeyondTrust/api/public/v3" ctx = _ctx(cfg) self.opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()), urllib.request.HTTPSHandler(context=ctx) if ctx else urllib.request.HTTPSHandler(), ) def _auth_header(self): return "PS-Auth key=" + str(self.cfg.get("api_key", "")) + "; runas=" + str(self.cfg.get("runas_user", "")) + ";" def signin(self): req = urllib.request.Request(self.base + "/Auth/SignAppin", data=b"", headers={"Authorization": self._auth_header(), "Accept": "application/json"}, method="POST") with self.opener.open(req, timeout=60) as r: raw = r.read() return json.loads(raw) if raw else {} def call(self, method, path, body=None, params=None): url = self.base + path if params: clean = {k: v for k, v in params.items() if v not in (None, "")} if clean: url += "?" + urllib.parse.urlencode(clean) data = json.dumps(body).encode("utf-8") if body is not None else None headers = {"Accept": "application/json", "Authorization": self._auth_header()} if data is not None: headers["Content-Type"] = "application/json" req = urllib.request.Request(url, data=data, headers=headers, method=method) with self.opener.open(req, timeout=60) as r: raw = r.read() return json.loads(raw) if raw else {} def signout(self): try: req = urllib.request.Request(self.base + "/Auth/Signout", data=b"", method="POST") self.opener.open(req, timeout=30).read() except Exception: pass def _run(fn): try: cfg = _cfg() inputs = _inputs() client = Client(cfg) client.signin() try: result = fn(client, inputs) finally: client.signout() print(json.dumps(result)) 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) def main(client, inputs): system_id = inputs.get("system_id") account_id = inputs.get("account_id") duration_minutes = inputs.get("duration_minutes") reason = inputs.get("reason") if not system_id: raise Exception("system_id is required") if not account_id: raise Exception("account_id is required") body = { "SystemId": int(system_id), "AccountId": int(account_id), "DurationMinutes": int(duration_minutes) if duration_minutes else 30, "Reason": reason or "Riposte SOAR", "AccessType": "View", } return client.call("POST", "/Requests", body=body) _run(main)