auth.py 20.6 KB
# -*- 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 次成功;
2026-10-28 09:54 连续 5 次在 0.03~0.12 秒内被断),所以拿到授权码后先等 token_exchange_delay 秒,网络错误时按
2/3/5/8/10/12/15 秒(±20% 抖动,约 1 分钟内,授权码仍有效)退避重试 token_exchange_retries 次(默认 7)。
这一步只用授权码,不涉及密码,重试不会锁号。每次失败都记录实际连的 IP 和断在哪个阶段(见 client.py)。
"""
import html as htmlmod
import json
import logging
import random
import re
import time
import urllib.parse

from ...infra.logutil import add_secret
from ..base import CaptchaWrong, LoginError, LoginRejected, Token  # noqa: F401  (保持 auth.LoginError 等旧引用可用)
from . import captcha, rsa_pkcs1

log = logging.getLogger("dmsfetch")
SUCCESS_CODE = "10000000"
BACKOFF = (2, 3, 5, 8, 10, 12, 15)          # 换 token 网络失败后的等待秒数(× retry_backoff/2)


# ----------------------------------------------------------------------------
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 _looks_like_image(body):
    """按常见图片魔数判断响应体是不是图片(Kaptcha.jpg 拉回来的验证码图片用)。"""
    if not body:
        return False
    return (body[:8] == b"\x89PNG\r\n\x1a\n" or body[:3] == b"\xff\xd8\xff" or
            body[:6] in (b"GIF87a", b"GIF89a") or body[:2] == b"BM")


# ---- 图片验证码(2026-11 真站抓包 + IAM 源码 main_index.js / smsCode_index.js 确认)----
#   * displayVerificationCode.do 返回纯文本 "true" / "false":要不要显示验证码(不是图片本身);
#   * 图片:登录页 <base href=".../idp/"> 下的 Kaptcha.jpg?dt=<毫秒时间戳>,验证码绑在当前 IAM 会话(Cookie)上;
#   * 没有验证码时浏览器照样提交 j_checkcode 的占位值「验证码」;验证码 4 位、字母数字、区分大小写。
CHECKCODE_PLACEHOLDER = "验证码"
CAPTCHA_LENGTH = 4
_CAPTCHA_TIP_RE = re.compile(r"验证码|checkcode|kaptcha|captcha", re.I)


def _need_captcha(client, iam, headers, username, sp_code):
    """问 IAM 这个账号这次要不要验证码。返回 (要不要, 原始响应文本);网络错误按不要处理(提交时 IAM 会再拦)。"""
    r = client.request("POST", iam + "/idp/displayVerificationCode.do", headers=headers,
                       data=urllib.parse.urlencode({"j_username": username, "j_authMethodID": "1",
                                                    "spAuthChainCode": sp_code}), retries=0)
    text = (r.text or "").strip() if r.status == 200 else ""
    return text.lower() == "true", (text[:20] if text else "HTTP %s %s" % (r.status, r.error or ""))


def _captcha_url(html, login_url):
    return urllib.parse.urljoin(_base_href(html, login_url), "Kaptcha.jpg?dt=%d" % int(time.time() * 1000))


def _fetch_captcha_image(client, html, login_url):
    """拉一张新的验证码图片(和浏览器点图片刷新一样,每次一张新的;只是 GET 图片,不提交密码)。不是图片返回 None。"""
    r = client.request("GET", _captcha_url(html, login_url), retries=0,
                       headers={"Referer": login_url, "Accept": "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"})
    if r.status == 200 and _looks_like_image(r.body):
        return r.body
    log.warning("验证码图片没拉到(HTTP %s %s,%d 字节)", r.status, r.error or "", len(r.body or b""))
    return None


PROBE_WRONG_CODE = "0000"           # 探测 A 故意填的错误验证码


def _solve_captcha(client, cfg, iam, headers, html, login_url, sp_code, info, force=None):
    """要验证码就拉图 → 云端识别(有限重试),返回 (要填进 j_checkcode 的值, 是否带了验证码);不要验证码返回占位值。
    无法识别(开关关闭 / 云端不可用 / 次数用完)抛 LoginError——此时还没提交密码。
    force(只给 tool.bat 菜单 15「验证码提交探测」用):不管 IAM 要不要,都在本会话拉一张验证码;
      "wrong" = 故意填错(PROBE_WRONG_CODE),看 IAM 会不会校验;"recognize" = 识别后填写,看 IAM 接不接受。"""
    need, raw = _need_captcha(client, iam, headers, cfg.username, sp_code)
    info["need"] = need
    if not need and not force:
        log.info("本次登录不需要验证码(displayVerificationCode=%s),直接提交", raw)
        return CHECKCODE_PLACEHOLDER, False
    if force:
        log.warning("【验证码探测 %s】IAM 本次%s要求验证码(displayVerificationCode=%s),按探测要求拉图",
                    force, "" if need else "不", raw)
    if force == "wrong":
        img = _fetch_captcha_image(client, html, login_url)
        if not img:
            raise LoginError("验证码图片没拉到,探测没做(密码未提交)")
        log.warning("【验证码探测 wrong】已拉一张验证码,故意填 %s 提交", PROBE_WRONG_CODE)
        return PROBE_WRONG_CODE, True
    log.info("IAM 要求验证码,拉取验证码图片交给云端识别…" if need else "【验证码探测】拉取验证码图片交给云端识别…")
    try:
        code = captcha.fetch_and_recognize(lambda: _fetch_captcha_image(client, html, login_url), cfg,
                                           text_length=CAPTCHA_LENGTH, info=info)
    except captcha.CaptchaUnavailable as e:
        captcha.report_outcome(cfg, info, "not_submitted", str(e))
        err = LoginError("IAM 要求验证码,但当前无法识别(%s),请人工登录一次或稍后重试(密码未提交)" % e)
        err.submitted = False
        err.captcha = True
        raise err
    return code, True


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 现取(跳过被注释掉的旧公钥);取不到再用云端配置里的备用公钥。"""
    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 脚本取到公钥,改用配置里的备用公钥")
            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, force_captcha=None):
    """完整登录,返回 Token。网络类错误抛 LoginError;账号被拒抛 LoginRejected(不重试);验证码不对抛 CaptchaWrong。
    force_captcha 只给菜单 15「验证码提交探测」用(见 _solve_captcha)。"""
    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}))

    # 3.5) 验证码:IAM 按账号动态要求图片验证码(有时有、有时没有),见 _solve_captcha
    cinfo = {}
    checkcode, has_captcha = _solve_captcha(client, cfg, iam, dict(xhr, **form_ct), html, login_url, sp_code, cinfo,
                                            force_captcha)
    how = "probe_" + force_captcha if force_captcha else "api"

    # 4) 提交登录(只提交这 1 次;被拒绝就停)
    encrypted = rsa_pkcs1.encrypt_b64(n, e, cfg.password)
    add_secret(encrypted)
    fields = {"j_username": cfg.username, "j_password": encrypted, "j_checkcode": 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 = str(j.get("authnErrorTip") or j.get("authnInfo") or "")
        log.warning("IAM 登录未通过,原始提示:%s(响应字段 %s)", tip or "无", sorted(j.keys()))
        if _CAPTCHA_TIP_RE.search(tip):
            # 验证码错 / 需要验证码:不是账号密码问题,不能按「被拒」永久暂停;由 BaseSession 按每日上限控制再试
            captcha.report_outcome(cfg, cinfo, "captcha_wrong", tip, how)
            raise CaptchaWrong("IAM 提示验证码问题(%s;本次%s验证码,填的是 %s)"
                               % (tip, "有" if has_captcha else "没要求", checkcode if has_captcha else "占位值"))
        captcha.report_outcome(cfg, cinfo, "rejected", tip, how)
        raise LoginRejected("IAM 拒绝登录(账号或密码错误/账号被锁定等)。响应字段: %s %s" % (sorted(j.keys()), tip))
    if has_captcha:
        log.info("IAM 接受了这次提交(%s验证码 %s)", "探测" if force_captcha else "", checkcode)
        captcha.report_outcome(cfg, cinfo, "ok", "IAM 校验通过", how)

    # 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", 7)))
    scale = cfg.retry_backoff / 2.0                 # 默认 retry_backoff=2.0 → 2/3/5/8/10/12/15 秒
    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(BACKOFF[min(i, len(BACKOFF) - 1)] * scale * random.uniform(0.8, 1.2))
    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"))


def captcha_test(cfg, client):
    """验证码测试(tool.bat 菜单「验证码测试」用):拉一张验证码图片并识别,不提交密码、不登录。

    走和真实登录一致的链路:授权入口 → IAM 登录页 → displayVerificationCode.do 问要不要 → Kaptcha.jpg 拉图 → 云端识别。
    IAM 这次不要求验证码时也照样拉一张图识别(Kaptcha.jpg 随时能拉),方便检验识别效果。
    返回 dict:{ok, need_captcha, recognized, error, image_evidence_id, result_evidence_id}。"""
    iam = cfg.iam_base
    form_ct = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    out = {"ok": False, "need_captcha": False, "recognized": "", "error": ""}

    # 1) 到 IAM 登录页,取 spAuthChainCode
    resp, chain = client.follow("GET", authorize_url(cfg))
    if not _is_login_page(resp):
        return dict(out, error="没能到达 IAM 登录页(HTTP %s)" % resp.status)
    login_url = chain[-1]["url"]
    html = resp.text
    sp_code = _parse_sp_auth_chain_code(html)
    if not sp_code:
        return dict(out, error="登录页缺少 spAuthChainCode")
    xhr = {"X-Requested-With": "XMLHttpRequest", "Referer": login_url, "Origin": _origin(iam)}

    # 2) 与登录一致的预备请求 + 问要不要验证码
    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}))
    out["need_captcha"], out["display_result"] = _need_captcha(client, iam, dict(xhr, **form_ct), cfg.username, sp_code)

    # 3) 拉图 + 识别(只识别一次,不重试)
    img = _fetch_captcha_image(client, html, login_url)
    if not img:
        return dict(out, error="验证码图片没拉到(Kaptcha.jpg 不是图片)")
    try:
        r = captcha.recognize_detail(img, cfg, text_length=CAPTCHA_LENGTH)
    except captcha.CaptchaUnavailable as e:
        return dict(out, error="无法识别:%s" % e)
    except Exception as e:  # noqa: BLE001
        return dict(out, error="识别出错:%s" % e)
    text = r.get("text") or ""
    good = captcha.valid(text, CAPTCHA_LENGTH)
    out.update(recognized=text, ok=good, image_evidence_id=r.get("image_evidence_id"),
               result_evidence_id=r.get("result_evidence_id"), elapsed=r.get("elapsed"))
    if not good:
        out["error"] = r.get("error") or ("识别结果不是 %d 位字母数字:%r" % (CAPTCHA_LENGTH, text))
    return out