relay.py
10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# -*- coding: utf-8 -*-
"""浏览器里的 auth-api 请求改由取数端代发(带重试 / 缓存)。
为什么:门店 auth-api(172.16.255.22)会间歇性地秒断连接。人遇到时会刷新重试;DMS 前端 JS 不重试,
一个 iam-oauth / detail/perms / list/menu/current / list/user/systems 被断,页面就卡在 callback 或菜单出不来。
怎么做:截图浏览器开启 CDP Fetch 拦截(只拦 auth-api 域名,其它请求照常走浏览器):
* OPTIONS 预检:本地直接回 204 + CORS 头,不走网络(顺带少一半连接);
* 其它请求:放进代发队列,由取数端用 Python 串行发出,网络错误 / 502~504 按 1/2/3/5/8 秒退避重试,
成功后 Fetch.fulfillRequest 原样还给页面(补 CORS 头);
* GET 成功过的响应按(地址去掉随机参数 + 登录 token)缓存,实时请求重试全部失败时用缓存答复(权限、菜单、系统列表
这类只读数据);POST(如 iam-oauth 换 token)绝不缓存;
* 每次代发写审计(第几次、耗时、错误、是否用了缓存)并在抓包里标记「取数端代发」。
"""
import base64
import gzip
import json
import logging
import queue
import re
import threading
import time
import urllib.parse
import zlib
from ..connectors.gtmc.client import Client
from ..infra.logutil import add_secret
from ..infra.tokens import normalize_token
log = logging.getLogger("edge")
BACKOFF = (1, 2, 3, 5, 8, 8, 10, 10, 12, 15)
DROP_REQ = ("host", "content-length", "connection", "accept-encoding", "cookie", "proxy-connection")
DROP_RESP = ("content-length", "transfer-encoding", "connection", "content-encoding", "keep-alive")
def _cache_key(method, url, headers):
u = re.sub(r"([?&])(v|_|t|timestamp)=[^&]*", r"\1", url).rstrip("?&")
auth = next((v for k, v in headers.items() if k.lower() == "authorization"), "")
return "%s %s %s" % (method, u, auth[-24:])
class AuthRelay(object):
def __init__(self, chrome, cfg, prefixes, audit=None):
"""prefixes:要代发的地址前缀,如 ["https://auth-api.dms.gtmc.com.cn"](只拦以它开头的请求)。"""
self.chrome = chrome
self.cfg = cfg
self.hosts = [h.rstrip("/") for h in prefixes if h]
self.audit = audit
self.client = Client(cfg) # 代发专用客户端:和业务请求共用全局节拍(infra/ratelimit)
self.client.penalize = False # auth-api 间歇断连是已知问题(有自己的退避重试),不让它拖慢 / 暂停业务请求
self.retries = int(getattr(cfg, "relay_retries", 6))
self.cache = {}
self.preflights = 0
self.stats = {"relayed": 0, "ok": 0, "retried": 0, "failed": 0, "cached": 0}
self.issued_token = None # 代发 iam-oauth 成功时响应里的 token(浏览器拿到的就是它)
self._inflight = 0 # 已拦下、还没答复给页面的请求数(含正在退避重试的)
self._lock = threading.Lock()
self._q = queue.Queue()
self._stop = threading.Event()
self._worker = threading.Thread(target=self._work, name="auth-relay", daemon=True)
def start(self):
if not self.hosts:
return self
self.chrome.on("Fetch.requestPaused", self._on_paused)
patterns = [{"urlPattern": "%s/*" % h, "requestStage": "Request"} for h in self.hosts]
self.chrome.send("Fetch.enable", {"patterns": patterns})
self._worker.start()
log.info("auth-api 代发已开启(%s):浏览器访问这些地址时由取数端代发,断开自动重试 %d 次",
"、".join(self.hosts), self.retries)
return self
def stop(self):
self._stop.set()
self._q.put(None)
# ------------------------------------------------------------------ 拦截
def _on_paused(self, p):
req = p.get("request") or {}
if req.get("method") == "OPTIONS":
self.preflights += 1
h = {k.lower(): v for k, v in (req.get("headers") or {}).items()}
origin = h.get("origin") or "*"
hdrs = [{"name": "Access-Control-Allow-Origin", "value": origin},
{"name": "Access-Control-Allow-Credentials", "value": "true"},
{"name": "Access-Control-Allow-Methods", "value": h.get("access-control-request-method") or
"GET,POST,PUT,DELETE,OPTIONS"},
{"name": "Access-Control-Allow-Headers", "value": h.get("access-control-request-headers") or "*"},
{"name": "Access-Control-Max-Age", "value": "600"}]
self.chrome.send("Fetch.fulfillRequest", {"requestId": p["requestId"], "responseCode": 204,
"responseHeaders": hdrs})
return
with self._lock:
self._inflight += 1
self._q.put(p)
def busy(self):
"""还有代发请求在处理 / 重试中(页面在等它的答复,这时刷新页面会让答复作废)。"""
return self._inflight > 0
def _work(self):
while not self._stop.is_set():
p = self._q.get()
if p is None:
return
try:
self._relay(p)
except Exception as e: # noqa: BLE001
log.warning("代发出错(%s),交给浏览器自己发:%s", (p.get("request") or {}).get("url", "")[:80], e)
try:
self.chrome.send("Fetch.continueRequest", {"requestId": p["requestId"]})
except Exception: # noqa: BLE001
pass
finally:
with self._lock:
self._inflight -= 1
def _cookie_header(self, url):
try:
cs = self.chrome.send("Network.getCookies", {"urls": [url]}).get("cookies") or []
except Exception: # noqa: BLE001
return ""
return "; ".join("%s=%s" % (c["name"], c["value"]) for c in cs)
def _relay(self, p):
req = p.get("request") or {}
method, url = req.get("method", "GET"), req.get("url", "")
headers = {k: v for k, v in (req.get("headers") or {}).items() if k.lower() not in DROP_REQ}
cookie = self._cookie_header(url)
if cookie:
headers["Cookie"] = cookie
body = req.get("postData")
if body is None and req.get("hasPostData"):
try:
body = self.chrome.send("Fetch.getRequestPostData", {"requestId": p["requestId"]}).get("postData")
except Exception: # noqa: BLE001
body = None
short = urllib.parse.urlparse(url).path
key = _cache_key(method, url, headers)
self.stats["relayed"] += 1
t0 = time.time()
errors = []
resp = None
for i in range(self.retries + 1):
r = self.client.request(method, url, headers=headers, data=body, cookies=False, retries=0)
if r.status and r.status not in (502, 503, 504):
resp = r
break
errors.append(r.error or "HTTP %d" % r.status)
if i < self.retries:
self.stats["retried"] += 1
wait = BACKOFF[min(i, len(BACKOFF) - 1)]
log.warning("代发 %s %s 第 %d 次失败(%s),%d 秒后重试", method, short, i + 1, errors[-1], wait)
time.sleep(wait)
cached = False
if resp is None and method == "GET" and key in self.cache:
status, rh, rb = self.cache[key]
cached = True
self.stats["cached"] += 1
elif resp is None:
self.stats["failed"] += 1
msg = "代发 %s %s 重试 %d 次仍失败:%s" % (method, short, self.retries, ";".join(errors[-3:]))
log.error(msg)
self._note(p, "取数端代发失败:" + ";".join(errors[-3:]))
if self.audit:
self.audit.event("relay", msg, level="error", url=url, attempts=len(errors))
self.chrome.send("Fetch.failRequest", {"requestId": p["requestId"], "errorReason": "ConnectionClosed"})
return
else:
status, rh, rb = resp.status, resp.headers, resp.body
if method == "GET" and 200 <= status < 300:
self.cache[key] = (status, rh, rb)
self.stats["ok"] += 1
rb = self._decode(rh, rb)
if not cached and 200 <= status < 300 and "/auth/login/iam-oauth" in url:
self._remember_token(rb)
out = [{"name": k, "value": v} for k, v in rh if k.lower() not in DROP_RESP]
names = {h["name"].lower() for h in out}
origin = next((v for k, v in (req.get("headers") or {}).items() if k.lower() == "origin"), "")
if origin and "access-control-allow-origin" not in names:
out.append({"name": "Access-Control-Allow-Origin", "value": origin})
out.append({"name": "Access-Control-Allow-Credentials", "value": "true"})
out.append({"name": "Content-Length", "value": str(len(rb))})
self.chrome.send("Fetch.fulfillRequest", {"requestId": p["requestId"], "responseCode": int(status),
"responseHeaders": out,
"body": base64.b64encode(rb).decode("ascii")}, timeout=30)
note = "取数端代发:%s(%d 次尝试,%.1f 秒)" % ("用缓存答复" if cached else "HTTP %d" % status,
len(errors) + (0 if cached else 1), time.time() - t0)
self._note(p, note)
level = "warn" if (errors or cached) else "info"
if self.audit:
self.audit.event("relay", "%s %s → %s" % (method, short, note), level=level, url=url,
attempts=len(errors) + 1, errors=errors[-3:] or None, cached=cached or None)
def _remember_token(self, body):
try:
j = json.loads(body.decode("utf-8", "replace"))
tok = normalize_token(((j.get("body") or {}).get("value")) if isinstance(j, dict) else None)
except (ValueError, AttributeError):
tok = None
if tok:
add_secret(tok)
self.issued_token = tok
def _note(self, p, note):
har = getattr(self.chrome, "har", None)
if har and p.get("networkId"):
har.mark_relayed(p["networkId"], note)
@staticmethod
def _decode(headers, body):
enc = next((v for k, v in headers if k.lower() == "content-encoding"), "").lower()
try:
if enc == "gzip":
return gzip.decompress(body)
if enc == "deflate":
return zlib.decompress(body)
except Exception: # noqa: BLE001
pass
return body
def summary(self):
s = dict(self.stats, preflights=self.preflights)
return "代发 %(relayed)d 次:成功 %(ok)d,重试 %(retried)d 次,用缓存 %(cached)d,失败 %(failed)d;预检 %(preflights)d 次" % s