auth.py
12.7 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# -*- coding: utf-8 -*-
"""IAM 单点登录(OAuth2 授权码)→ token。链路与探针 v2.1 在真实系统上验证过的一致:
1. GET /idp/oauth2/authorize?...client_id=S-80 -> 302 ... -> IAM 登录页(带 authnLcKey)
2. 登录页取 spAuthChainCode(switchAuthTab('1','<hex>'))、authen1Form action、crypt.js 里的 RSA 公钥
3. POST /idp/authcenter/ActionAuthChain?authnLcKey= (j_password=RSA 密文) -> {"loginFailed":"false"}
4. POST authen1Form 的 action(同样的表单) -> 302 ... -> dms 回调 ?code=<授权码>
5. POST auth-api /auth/login/iam-oauth {"code":...} -> body.value 即 JWT(不带 Bearer 前缀)
第 0 步(可关):像浏览器一样先打开一次 DMS 首页。
第 5 步:门店实测 auth-api 会间歇性地不回应就断开连接(2026-10-21 14:39:第 1、2 次断开、第 3 次成功;
网络诊断里连 TLS 握手都会被断开),所以拿到授权码后先等 token_exchange_delay 秒,网络错误时按 3/5/8/10 秒退避
重试 token_exchange_retries 次。这一步只用授权码,不涉及密码,重试不会锁号。
"""
import html as htmlmod
import json
import logging
import random
import re
import time
import urllib.parse
from . import rsa_pkcs1
from .logutil import add_secret
log = logging.getLogger("dmsfetch")
SUCCESS_CODE = "10000000"
class LoginError(Exception):
"""登录流程失败(网络/页面结构变化等),可由上层决定是否重试。"""
class LoginRejected(LoginError):
"""IAM 明确拒绝(账号或密码错误等)。**不要重试**,避免触发锁号。"""
class Token(object):
def __init__(self, value, expires_at=None, token_type="bearer"):
self.value = value
self.expires_at = expires_at # epoch 秒;未知为 None
self.token_type = token_type
@property
def header_value(self):
return "Bearer " + self.value
def expires_soon(self, margin_seconds=300):
return self.expires_at is not None and time.time() > self.expires_at - margin_seconds
# ----------------------------------------------------------------------------
def _origin(url):
p = urllib.parse.urlparse(url)
return "%s://%s" % (p.scheme, p.netloc)
def authorize_url(cfg):
"""与 DMS 前端 JS 完全一致的授权入口(redirect_uri 不做 URL 编码)。"""
callback = urllib.parse.urljoin(cfg.dms_url, "iam/auth/callback")
return "%s/idp/oauth2/authorize?state=%d&response_type=code&redirect_uri=%s&client_id=%s" % (
cfg.iam_base, random.randint(10, 99), callback, cfg.client_id)
def _is_login_page(resp):
return resp.status == 200 and ("j_username" in resp.text or "j_password" in resp.text)
def _base_href(html, page_url):
m = re.search(r"<base\b[^>]*\bhref\s*=\s*[\"']([^\"']+)[\"']", html, re.I)
return urllib.parse.urljoin(page_url, m.group(1)) if m else page_url
def _script_srcs(html, page_url):
base = _base_href(html, page_url)
return [urllib.parse.urljoin(base, m.group(1))
for m in re.finditer(r"<script\b[^>]*\bsrc\s*=\s*[\"']([^\"']+)[\"']", html, re.I)]
def _parse_sp_auth_chain_code(html):
# 页面把"账号密码"这套认证链的 code 放在 switchAuthTab('1','<hex>');input 的 value 是空的
for pat in (r"switchAuthTab\(\s*[\"']1[\"']\s*,\s*[\"']([0-9a-fA-F]{16,})[\"']",
r"name=[\"']spAuthChainCode[\"'][^>]*value=[\"']([0-9a-fA-F]{16,})[\"']"):
m = re.search(pat, html)
if m:
return m.group(1)
return None
def _parse_authn_key(login_url, html):
q = urllib.parse.parse_qs(urllib.parse.urlparse(login_url).query)
if q.get("authnLcKey"):
return q["authnLcKey"][0]
m = re.search(r"id=[\"']authnLcKey[\"'][^>]*value=[\"']([^\"']+)[\"']", html)
return m.group(1) if m else None
def _parse_form_action(html, login_url):
mf = re.search(r"<form\b[^>]*\bid\s*=\s*[\"']authen1Form[\"'][^>]*>", html, re.I)
if not mf:
return None
ma = re.search(r"\baction\s*=\s*([\"'])(.*?)\1", mf.group(0), re.I | re.S)
if not ma:
return None
return urllib.parse.urljoin(_base_href(html, login_url), htmlmod.unescape(ma.group(2)))
def _get_public_key(client, cfg, html, login_url):
"""优先从 crypt.js 现取(跳过被注释掉的旧公钥);取不到再用 config.ini 里的备用公钥。"""
host = urllib.parse.urlparse(login_url).netloc
srcs = [u for u in _script_srcs(html, login_url) if urllib.parse.urlparse(u).netloc == host]
crypt = [u for u in srcs if "crypt" in u.split("?")[0].rsplit("/", 1)[-1].lower()]
# crypt.js 优先;没找到再最多扫 8 个其它脚本(jquery 等通用库不会有公钥,跳过)
others = [u for u in srcs if u not in crypt
and not re.search(r"jquery|jsencrypt|tripledes|mode-ecb|u2f|ddLogin|messages_zh", u, re.I)]
for u in crypt + others[:8]:
r = client.request("GET", u, headers={"Referer": login_url})
if r.status == 200:
key = rsa_pkcs1.find_active_pubkey(r.text)
if key:
log.info("RSA 公钥取自 %s(%d 位)", u.split("?")[0].rsplit("/", 1)[-1], key[0].bit_length())
return key
if cfg.fallback_public_key:
key = rsa_pkcs1.parse_pubkey_b64(cfg.fallback_public_key)
if key:
log.warning("没能从 IAM 脚本取到公钥,改用 config.ini 里的备用公钥")
return key
raise LoginError("取不到 RSA 公钥(IAM 页面结构可能变了)")
def _code_from_chain(chain):
for c in chain:
for cand in (c["location"], c["url"]):
if cand and re.search(r"[?&]code=", cand):
code = urllib.parse.parse_qs(urllib.parse.urlparse(cand).query).get("code", [""])[0]
if code:
return code
return None
# ----------------------------------------------------------------------------
def login(client, cfg):
"""完整登录,返回 Token。网络类错误抛 LoginError;账号被拒抛 LoginRejected(不重试)。"""
add_secret(cfg.password)
iam = cfg.iam_base
started = time.time()
# 0) 与浏览器一致:先打开 DMS 首页(失败不影响,只记日志)
if getattr(cfg, "warmup_dms", True):
r = client.request("GET", cfg.dms_url, headers={"Accept": "text/html,application/xhtml+xml,*/*;q=0.8"},
retries=0)
if r.status != 200:
log.warning("打开 DMS 首页异常(HTTP %s %s),继续登录", r.status, r.error or "")
# 1) 授权入口 → IAM 登录页
resp, chain = client.follow("GET", authorize_url(cfg))
if not _is_login_page(resp):
raise LoginError("没能到达 IAM 登录页(HTTP %s,终点 %s)" % (resp.status, chain[-1]["url"].split("?")[0]))
login_url = chain[-1]["url"]
html = resp.text
# 2) 解析登录页
authn_key = _parse_authn_key(login_url, html)
sp_code = _parse_sp_auth_chain_code(html)
if not authn_key or not sp_code:
raise LoginError("登录页缺少 authnLcKey/spAuthChainCode(IAM 页面结构可能变了)")
add_secret(authn_key)
action = _parse_form_action(html, login_url) or (
"%s/idp/AuthnEngine?currentAuth=urn_oasis_names_tc_SAML_2.0_ac_classes_BAMUsernamePassword"
"&authnLcKey=%s&entityId=%s" % (iam, authn_key, cfg.entity_id))
n, e = _get_public_key(client, cfg, html, login_url)
# 3) 与浏览器一致的预备请求(失败不影响)
xhr = {"X-Requested-With": "XMLHttpRequest", "Referer": login_url, "Origin": _origin(iam)}
form_ct = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
client.request("GET", iam + "/idp/dingdingInitData.do", headers=xhr)
client.request("POST", iam + "/idp/federalTrust/getLoginPageData",
headers=dict(xhr, **form_ct), data=urllib.parse.urlencode({"entityId": cfg.entity_id}))
client.request("POST", iam + "/idp/displayVerificationCode.do", headers=dict(xhr, **form_ct),
data=urllib.parse.urlencode({"j_username": cfg.username, "j_authMethodID": "1",
"spAuthChainCode": sp_code}))
# 4) 提交登录(只提交这 1 次;被拒绝就停)
encrypted = rsa_pkcs1.encrypt_b64(n, e, cfg.password)
add_secret(encrypted)
fields = {"j_username": cfg.username, "j_password": encrypted, "j_checkcode": "验证码",
"op": "login", "spAuthChainCode": sp_code, "authnLcKey": authn_key}
body = urllib.parse.urlencode(fields)
r = client.request("POST", "%s/idp/authcenter/ActionAuthChain?authnLcKey=%s" % (iam, authn_key),
headers=dict(xhr, **form_ct), data=body, retries=0)
if r.status == 0:
raise LoginError("登录请求网络失败: %s" % r.error)
j = r.json()
if not isinstance(j, dict):
raise LoginError("登录响应不是 JSON(HTTP %s)" % r.status)
if str(j.get("loginFailed", "")).lower() != "false":
tip = j.get("authnErrorTip") or j.get("authnInfo") or ""
raise LoginRejected("IAM 拒绝登录(账号或密码错误/账号被锁定等)。响应字段: %s %s" % (sorted(j.keys()), tip))
# 5) 浏览器随后会把整个 authen1Form POST 到 action,IAM 302 回带 code 的回调
def stop(loc):
return bool(re.search(r"[?&]code=", loc))
page_hdr = {"Content-Type": "application/x-www-form-urlencoded", "Origin": _origin(iam),
"Referer": login_url, "Upgrade-Insecure-Requests": "1",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}
_, chain = client.follow("POST", action, headers=page_hdr, data=body, stop_when=stop, retries=0)
code = _code_from_chain(chain)
if not code: # 兜底:已有 IAM 会话时,重访授权入口/登录页也应 302 回带 code
for u in (login_url, authorize_url(cfg)):
_, chain = client.follow("GET", u, headers={"Referer": login_url}, stop_when=stop)
code = _code_from_chain(chain)
if code:
break
if not code:
raise LoginError("登录已通过校验,但没拿到授权码 code")
add_secret(code)
# 6) code 换 token(与浏览器一致带 Cookie;auth-api 间歇断连,网络错误时退避重试)
got_code = time.time()
log.info("IAM 校验通过,已拿到授权码,正在换 token(%s)", cfg.auth_api)
callback = "%siam/auth/callback?code=%s&state=%d" % (cfg.dms_url, code, random.randint(10, 99))
hdr_json = {"Content-Type": "application/json;charset=UTF-8",
"Accept": "application/json, text/plain, */*",
"Origin": _origin(cfg.dms_url), "Referer": callback}
delay = float(getattr(cfg, "token_exchange_delay", 0) or 0)
if delay > 0:
time.sleep(delay)
tries = 1 + max(0, int(getattr(cfg, "token_exchange_retries", 4)))
scale = cfg.retry_backoff / 2.0 # 默认 retry_backoff=2.0 → 3/5/8/10 秒
errors = []
for i in range(tries):
r = client.request("POST", cfg.auth_api + "/auth/login/iam-oauth", data=json.dumps({"code": code}),
headers=hdr_json, retries=0)
since = time.time() - got_code
if r.status != 0 and r.status not in (502, 503, 504):
if i:
log.info("换 token 第 %d 次尝试成功(距拿到授权码 %.1f 秒)", i + 1, since)
break
why = r.error or "HTTP %d" % r.status
errors.append("第%d次(距授权码%.0f秒): %s" % (i + 1, since, why))
log.warning("换 token 请求失败 %d/%d(距拿到授权码 %.1f 秒):%s", i + 1, tries, since, why)
if i + 1 < tries:
time.sleep((3, 5, 8, 10)[min(i, 3)] * scale)
else:
raise LoginError("换 token 请求网络失败(IAM 账号密码已校验通过,卡在 %s/auth/login/iam-oauth):%s"
% (cfg.auth_api, ";".join(errors)))
j = r.json()
hdr = (j or {}).get("header") or {} if isinstance(j, dict) else {}
body_ = (j or {}).get("body") if isinstance(j, dict) else None
if str(hdr.get("code")) != SUCCESS_CODE or not isinstance(body_, dict) or not body_.get("value"):
raise LoginError("换 token 失败: HTTP %s code=%s message=%s" % (r.status, hdr.get("code"), hdr.get("message")))
value = str(body_["value"])
if value.lower().startswith("bearer "):
value = value[7:]
add_secret(value)
expires_in = body_.get("expiresIn")
try:
expires_at = time.time() + float(expires_in)
except (TypeError, ValueError):
expires_at = None
log.info("登录成功(%.1f 秒),token 有效期约 %s 小时", time.time() - started,
"%.1f" % (float(expires_in) / 3600) if expires_in else "未知")
return Token(value, expires_at, str(body_.get("tokenType") or "bearer"))