import json, os, sys, time, urllib.parse, urllib.request, urllib.error import jwt TOKEN_URL = "https://oauth2.googleapis.com/token" SCOPE = "https://www.googleapis.com/auth/cloud-platform" COMPUTE = "https://compute.googleapis.com/compute/v1" def _cfg(): return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}")) def _inputs(): return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}")) def _token(cfg): raw = cfg.get("service_account_json", "") sa = json.loads(raw) if isinstance(raw, str) else raw if not sa.get("client_email") or not sa.get("private_key"): raise Exception("service_account_json must contain client_email and private_key") now = int(time.time()) aud = sa.get("token_uri") or TOKEN_URL payload = { "iss": sa["client_email"], "scope": SCOPE, "aud": aud, "iat": now, "exp": now + 3600, } assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256") data = urllib.parse.urlencode({ "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": assertion, }).encode("utf-8") req = urllib.request.Request(aud, data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST") with urllib.request.urlopen(req, timeout=60) as r: tok = json.loads(r.read()) if not tok.get("access_token"): raise Exception("Token request failed: " + json.dumps(tok)) return tok["access_token"] def api(method, url, cfg, body=None, params=None): q = {k: str(v) for k, v in (params or {}).items() if v not in (None, "")} if q: url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q) data = json.dumps(body).encode("utf-8") if body is not None else None headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(cfg)} if data is not None: headers["Content-Type"] = "application/json" 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(fn): try: print(json.dumps(fn(_cfg(), _inputs()))) 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) proj = lambda cfg: str(cfg.get("project_id", "")) def _csv(v): return [s.strip() for s in str(v).split(",") if s.strip()] def main(cfg, inputs): name = inputs.get("name") if not name: raise Exception("name is required") network = inputs.get("network") or "default" direction = inputs.get("direction") or "INGRESS" action = inputs.get("action") or "deny" protocol = inputs.get("protocol") or "all" ports = _csv(inputs.get("ports", "")) ranges = _csv(inputs.get("ranges", "")) priority = inputs.get("priority", 1000) target_tags = _csv(inputs.get("target_tags", "")) rule_entry = {"IPProtocol": protocol or "all"} if ports: rule_entry["ports"] = ports key = "allowed" if action == "allow" else "denied" body = { "name": name, "network": "global/networks/" + (network or "default"), "direction": direction or "INGRESS", "priority": int(priority), key: [rule_entry], } ranges_list = ranges or ["0.0.0.0/0"] if (direction or "INGRESS") == "EGRESS": body["destinationRanges"] = ranges_list else: body["sourceRanges"] = ranges_list if target_tags: body["targetTags"] = target_tags url = COMPUTE + "/projects/{}/global/firewalls".format(proj(cfg)) return api("POST", url, cfg, body=body) _run(main)