|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, |
| 13 | +# software distributed under the License is distributed on an |
| 14 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | +# KIND, either express or implied. See the License for the |
| 16 | +# specific language governing permissions and limitations |
| 17 | +# under the License. |
| 18 | + |
| 19 | +"""Capture gh HTTP failures without changing stdout, exit status, or retry policy.""" |
| 20 | + |
| 21 | +import json |
| 22 | +import os |
| 23 | +import re |
| 24 | +import subprocess |
| 25 | +import sys |
| 26 | +import time |
| 27 | +import uuid |
| 28 | +from datetime import datetime, timezone |
| 29 | +from pathlib import Path |
| 30 | +from urllib.parse import urlsplit |
| 31 | + |
| 32 | +LIMIT = 65536 |
| 33 | +HEADERS = { |
| 34 | + "content-type", "content-length", "date", "x-github-request-id", |
| 35 | + "retry-after", "x-ratelimit-limit", "x-ratelimit-remaining", |
| 36 | + "x-ratelimit-reset", "x-ratelimit-resource", |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +def redact(value): |
| 41 | + if isinstance(value, bytes): |
| 42 | + value = value.decode("utf-8", errors="replace") |
| 43 | + value = value or "" |
| 44 | + # Artifacts do not inherit Actions' secret masker. Never store the request |
| 45 | + # headers or body; also redact credentials echoed by an error response. |
| 46 | + for name, secret in os.environ.items(): |
| 47 | + if re.search(r"(?:TOKEN|SECRET|PASSWORD|(?:^|_)KEY|(?:^|_)AK|(?:^|_)SK)$", name) and secret: |
| 48 | + for encoded in (secret, json.dumps(secret)[1:-1]): |
| 49 | + value = value.replace(encoded, "[REDACTED]") |
| 50 | + value = re.sub(r"\b(?:gh[pousr]_[A-Za-z0-9]+|github_pat_[A-Za-z0-9_]+)\b", "[REDACTED]", value) |
| 51 | + value = re.sub( |
| 52 | + r'(?i)(["\']?(?:access_token|refresh_token|id_token|token|api_key|secret|' |
| 53 | + r'client_secret|password|authorization|cookie|set-cookie)["\']?\s*[:=]\s*)' |
| 54 | + r'("(?:\\.|[^"\\])*"|[^\r\n,}]+)', r'\1"[REDACTED]"', value, |
| 55 | + ) |
| 56 | + value = re.sub(r"(https?://)[^/\s:@]+:[^/@\s]+@", r"\1[REDACTED]@", value) |
| 57 | + value = re.sub(r"(?i)([?&](?:token|access_token|signature|sig|key)=)[^&\s\"']+", r"\1[REDACTED]", value) |
| 58 | + return value |
| 59 | + |
| 60 | + |
| 61 | +def excerpt(value): |
| 62 | + value = redact(value) |
| 63 | + return value[:LIMIT] + ("\n[truncated]" if len(value) > LIMIT else "") |
| 64 | + |
| 65 | + |
| 66 | +def split_trace(stderr): |
| 67 | + """Keep only the final HTTP exchange; discard every outgoing header/body. |
| 68 | +
|
| 69 | + GH_DEBUG=api writes HTTP diagnostics to stderr, independently of gh api's |
| 70 | + response parser. Its body is a formatted, size-limited debug excerpt, not |
| 71 | + a byte-for-byte copy. Unknown debug formatting is discarded, never dumped. |
| 72 | + """ |
| 73 | + text = stderr.decode("utf-8", errors="replace") if isinstance(stderr, bytes) else (stderr or "") |
| 74 | + response = {"method": None, "path": None, "status": None, "headers": {}, |
| 75 | + "body_excerpt": "", "body_source": "gh_debug", "request_count": 0} |
| 76 | + ordinary = [] |
| 77 | + mode = "ordinary" |
| 78 | + body = [] |
| 79 | + body_chars = 0 |
| 80 | + for line in text.splitlines(): |
| 81 | + if line.startswith("* Request at "): |
| 82 | + count = response["request_count"] + 1 |
| 83 | + response = {**response, "method": None, "path": None, "status": None, |
| 84 | + "headers": {}, "body_excerpt": "", "request_count": count} |
| 85 | + body = [] |
| 86 | + body_chars = 0 |
| 87 | + response.pop("body_truncated", None) |
| 88 | + mode = "request" |
| 89 | + elif line.startswith("> "): |
| 90 | + match = re.match(r"> ([A-Z]+) (\S+) HTTP/", line) |
| 91 | + if match: |
| 92 | + response["method"] = match[1] |
| 93 | + response["path"] = redact(urlsplit(match[2]).path) |
| 94 | + mode = "request" |
| 95 | + elif re.match(r"< HTTP/\S+ \d{3}", line): |
| 96 | + response["status"] = int(line.split()[2]) |
| 97 | + response["headers"] = {} |
| 98 | + body = [] |
| 99 | + body_chars = 0 |
| 100 | + mode = "headers" |
| 101 | + elif mode == "headers" and line.startswith("< "): |
| 102 | + name, sep, value = line[2:].partition(":") |
| 103 | + if sep and name.lower() in HEADERS: |
| 104 | + response["headers"][name.lower()] = excerpt(value.strip()) |
| 105 | + elif line.startswith("* Request took "): |
| 106 | + mode = "ordinary" |
| 107 | + elif mode == "headers" and not line: |
| 108 | + mode = "body" |
| 109 | + elif mode == "body": |
| 110 | + # Bound retained response content even if debug output grows. |
| 111 | + line = redact(line) # Redact before truncation can split a secret. |
| 112 | + if body_chars < LIMIT: |
| 113 | + response["body_truncated"] = len(line) + body_chars > LIMIT |
| 114 | + body.append(line[:LIMIT - body_chars]) |
| 115 | + body_chars += len(line) + 1 |
| 116 | + else: |
| 117 | + response["body_truncated"] = True |
| 118 | + elif mode == "ordinary" and not line.startswith("* "): |
| 119 | + ordinary.append(line) |
| 120 | + response["body_excerpt"] = excerpt("\n".join(body).strip()) |
| 121 | + if mode == "request": |
| 122 | + # A transport failure has no response; do not mistake request data for |
| 123 | + # its body. subprocess timeout/type still identifies the failure. |
| 124 | + response["body_excerpt"] = "" |
| 125 | + return response, excerpt("\n".join(ordinary).strip()) |
| 126 | + |
| 127 | + |
| 128 | +def record_failure(command, error, stdout="", stderr="", *, diagnostic=None): |
| 129 | + response, ordinary = split_trace(stderr) if diagnostic is None else (diagnostic, excerpt(stderr)) |
| 130 | + record = { |
| 131 | + "time": datetime.now(timezone.utc).isoformat(), |
| 132 | + "run_id": os.environ.get("GITHUB_RUN_ID"), |
| 133 | + "run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT"), |
| 134 | + "job": os.environ.get("GITHUB_JOB"), |
| 135 | + "gh_version": os.environ.get("REVIEW_GH_VERSION"), |
| 136 | + "error_type": type(error).__name__, |
| 137 | + "returncode": getattr(error, "returncode", None), |
| 138 | + "timeout_seconds": getattr(error, "timeout", None), |
| 139 | + "http": response, |
| 140 | + "stderr": ordinary, |
| 141 | + "stdout_excerpt": excerpt(stdout), |
| 142 | + } |
| 143 | + # Do not record argv: -f/--body/--input can contain credentials or entire |
| 144 | + # reviews. Endpoint metadata comes only from the outgoing request line. |
| 145 | + summary = ( |
| 146 | + f"GitHub request failed: {response['method'] or 'unknown'} {response['path'] or 'unknown'}; " |
| 147 | + f"HTTP={response['status']}; request_id={response['headers'].get('x-github-request-id', 'unknown')}; " |
| 148 | + f"{record['error_type']}; exit={record['returncode']}; timeout={record['timeout_seconds']}" |
| 149 | + ) |
| 150 | + record["summary"] = redact(summary) |
| 151 | + directory = os.environ.get("REVIEW_GITHUB_DIAGNOSTICS_DIR") |
| 152 | + if directory: |
| 153 | + try: |
| 154 | + path = Path(directory) |
| 155 | + path.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 156 | + data = json.dumps(record, ensure_ascii=True, indent=2) + "\n" |
| 157 | + # Unique files support concurrent helper calls without append races. |
| 158 | + filename = path / f"{time.time_ns()}-{uuid.uuid4().hex}.json" |
| 159 | + with open(filename, "x", opener=lambda p, f: os.open(p, f, 0o600)) as handle: |
| 160 | + handle.write(data) |
| 161 | + except OSError as exc: |
| 162 | + print(f"Could not persist GitHub diagnostic ({type(exc).__name__})", file=sys.stderr) |
| 163 | + print(record["summary"], file=sys.stderr, flush=True) |
| 164 | + return ordinary, record |
| 165 | + |
| 166 | + |
| 167 | +def run_gh(command, **kwargs): |
| 168 | + """subprocess.run contract for captured text gh calls, with failure evidence.""" |
| 169 | + env = dict(kwargs.pop("env", os.environ)) |
| 170 | + env.update(GH_DEBUG="api", NO_COLOR="1") |
| 171 | + try: |
| 172 | + result = subprocess.run(command, env=env, **kwargs) |
| 173 | + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: |
| 174 | + ordinary, record = record_failure(command, error, error.stdout, error.stderr) |
| 175 | + error.stderr = ordinary + "\n" + record["summary"] |
| 176 | + # Preserve the original return code/timeout and stdout for callers. |
| 177 | + raise |
| 178 | + except OSError as error: |
| 179 | + record_failure(command, error) |
| 180 | + raise |
| 181 | + response, ordinary = split_trace(result.stderr) |
| 182 | + result.stderr = ordinary |
| 183 | + result.github_response = response |
| 184 | + return result |
| 185 | + |
| 186 | + |
| 187 | +def decode_json(result, command): |
| 188 | + try: |
| 189 | + return json.loads(result.stdout) |
| 190 | + except json.JSONDecodeError as error: |
| 191 | + record_failure(command, error, result.stdout, result.stderr, |
| 192 | + diagnostic=result.github_response) |
| 193 | + raise |
| 194 | + |
| 195 | + |
| 196 | +def main(): |
| 197 | + command = ["gh", *sys.argv[1:]] |
| 198 | + try: |
| 199 | + result = run_gh(command, capture_output=True, text=True, check=True) |
| 200 | + except subprocess.CalledProcessError as error: |
| 201 | + sys.stdout.write(error.stdout or "") |
| 202 | + print(error.stderr, file=sys.stderr) |
| 203 | + return error.returncode if error.returncode >= 0 else 128 - error.returncode |
| 204 | + except OSError as error: |
| 205 | + print(f"Could not execute gh ({type(error).__name__})", file=sys.stderr) |
| 206 | + return 1 |
| 207 | + sys.stdout.write(result.stdout) |
| 208 | + if result.stderr: |
| 209 | + print(result.stderr, file=sys.stderr) |
| 210 | + return 0 |
| 211 | + |
| 212 | + |
| 213 | +if __name__ == "__main__": |
| 214 | + sys.exit(main()) |
0 commit comments