Skip to main content

futu_backend/auth/
repull.rs

1//! v1.4.93 G2 (CLAUDE.md C4 audit): 实装 POST `/authority/repull_auth_code`,
2//! 对齐 C++ FTLogin `auth_impl.cpp:715-754` `RepullAuthCode` +
3//! `auth_impl.cpp:3308-3376` `ParseRepullAuthCodeResponse`。
4//!
5//! ## 触发场景
6//!
7//! - **broker auth_code 过期**:[`super::BrokerAuthCode::invalid_time`] 在认证
8//!   响应里给的 expiry。daemon 长跑(典型 30 天)触发,原本 broker channel
9//!   失效不 self-heal、必须重启 daemon —— 本 fn 让 `bridge` 拉新 auth_code
10//!   重做 `broker_auth` HTTP + CMD 1001 重登 broker, **避免重启**。
11//! - **broker `kAuthNoValidCid` (error_code=20029)**:C++ 在
12//!   `ParseRepullAuthCodeResponse` 见此码会 `ClearBrokerAccountInfo` 然后重新
13//!   走整 RepullAuthCode 流程 —— 本 fn 仅做"拉新 auth_code"那一步,
14//!   `ClearBrokerAccountInfo` 等价物(清 cipher / customer_id)由 caller 决定
15//!   要不要做(v1.4.93 不主动清,v1.4.94+ 视真机行为再决定)。
16//!
17//! ## 协议层 (对齐 C++)
18//!
19//! ```text
20//! POST https://{auth_domain}/authority/repull_auth_code
21//! body = {
22//!   "uid":       <u64>,            // 当前账户 uid
23//!   "device_id": "<16-hex>",       // 设备 ID (持久化)
24//!   "web_sig":   "<str>",          // /authority/ 响应里 web_sig_new (持久化)
25//!   "broker_id": <i32>             // 单 broker
26//! }
27//! ```
28//!
29//! Response result 单 broker:
30//! ```text
31//! { "result": { "uid":<u64>, "broker_id":<i32>, "auth_code":"<str>",
32//!   "invalid_time":<u64> } }
33//! ```
34//!
35//! 错误响应 result 缺失,error.error_code 给具体错码。
36//! `error_code=20029` (`kAuthNoValidCid`) 是特定可识别状态。
37//!
38//! ## Failure fallback
39//!
40//! - `web_sig` 空(v1.4.92 凭据 / device-verify shell 没此字段)→ caller 跳过
41//!   repull,fallback 走 platform refresh(重 POST /authority/)然后再 retry
42//! - HTTP 失败 / web_sig 过期 → caller log + 不重试本轮 → 等下次 broker
43//!   reconnect 触发或 platform refresh
44//!
45//! ## CLAUDE.md pitfalls 关联
46//!
47//! - **#34** Agent 调研结论 ≠ 真机正确性: 本实装基于 C++ 源码 `auth_impl.cpp`
48//!   完整对照, 但 backend 实际 wire (是否 reject 'web_sig over-frequent
49//!   refresh', error_code 准确含义) 仍需真机 verify
50//! - **#42** Backend-semantic 风险: error_code=20029 是否真触发 + repull 后
51//!   的 broker channel 重建是否 work, 需真机
52//! - **#45** Silent-success: 函数返 `Ok(BrokerAuthCode)` 必须基于响应
53//!   `result.auth_code` + `invalid_time` 都非空, 否则返 Err
54
55use futu_core::error::{FutuError, Result};
56
57use super::redact::uid_log_fingerprint;
58use super::{BrokerAuthCode, UserAttribution};
59
60/// `RepullAuthCode` URL 路径常量, 对齐 C++ `auth_impl.cpp:28`
61/// `AUTH_REPULL_AUTHCODE = "/authority/repull_auth_code"`.
62const REPULL_AUTH_CODE_PATH: &str = "/authority/repull_auth_code";
63
64/// C++ `kAuthNoValidCid` 错码(broker cid 失效)。当 backend 返此码时,
65/// 调用方应当清 broker cipher cache + 触发 broker channel 重建(C++ 行为
66/// `ClearBrokerAccountInfo`)。本 fn 不做副作用,只透传给 caller 决定。
67pub const ERROR_CODE_NO_VALID_CID: i64 = 20029;
68
69/// 请求新的 broker auth_code,对齐 C++ `RepullAuthCode`.
70///
71/// # 参数
72///
73/// - `http`: 复用 bridge 创建的 reqwest::Client(含 webpki-roots TLS 配置)
74/// - `attribution`: 当前账户 user_attribution (决定 auth_domain)
75/// - `uid`: 当前账户 uid (== AuthResult.user_id)
76/// - `web_sig`: 持久化的 web_sig (来自 SavedCredentials.web_sig 或
77///   AuthResult.web_sig)。**空字符串 → 直接 Err**(向后兼容旧凭据无此字段
78///   的场景,调用方应跳过 repull、fallback 走 platform refresh)。
79/// - `device_id`: 设备 ID (16-hex)
80/// - `broker_id`: 目标 broker (1001 / 1007 / 1008 / 1009 / 1012 / 1017 / 1019)
81///
82/// # 返回
83///
84/// 成功: `BrokerAuthCode { broker_id, auth_code, invalid_time }` —— 与
85/// `parse_auth_code_list` 解出的元素同结构, caller 可直接走 `broker_auth`
86/// HTTP + `broker_tcp_login` 流程。
87///
88/// 失败: `Err(FutuError::*)`. 见模块文档 fallback 策略.
89pub async fn repull_auth_code(
90    http: &reqwest::Client,
91    attribution: UserAttribution,
92    uid: u64,
93    web_sig: &str,
94    device_id: &str,
95    broker_id: u32,
96) -> Result<BrokerAuthCode> {
97    // Backward-compatible public wrapper: callers created before v1.4.112 did
98    // not pass OpenD's app client type. Internal bridge code should call the
99    // precise helper below because it already owns `AuthState.client_type`.
100    let client_type = match attribution {
101        UserAttribution::Cn | UserAttribution::Hk => 40,
102        _ => 60,
103    };
104    repull_auth_code_with_client_type(
105        http,
106        client_type,
107        attribution,
108        uid,
109        web_sig,
110        device_id,
111        broker_id,
112    )
113    .await
114}
115
116/// 请求新的 broker auth_code, 显式使用 OpenD client_type 构造 C++ 形态
117/// FTAuthImpl business headers。
118pub async fn repull_auth_code_with_client_type(
119    http: &reqwest::Client,
120    client_type: u8,
121    attribution: UserAttribution,
122    uid: u64,
123    web_sig: &str,
124    device_id: &str,
125    broker_id: u32,
126) -> Result<BrokerAuthCode> {
127    // 早期 reject: web_sig 空(向后兼容)
128    if web_sig.is_empty() {
129        return Err(FutuError::Codec(
130            "repull_auth_code: web_sig empty (legacy credentials before v1.4.93 G3 \
131             or device-verify shell path) — caller should fallback to platform refresh"
132                .into(),
133        ));
134    }
135    if uid == 0 {
136        return Err(FutuError::Codec(
137            "repull_auth_code: uid is 0 (invalid)".into(),
138        ));
139    }
140    if super::broker_config(broker_id).is_none() {
141        return Err(FutuError::Codec(format!(
142            "repull_auth_code: unknown broker_id {broker_id}"
143        )));
144    }
145
146    let url = repull_auth_code_url(attribution);
147
148    let body = serde_json::json!({
149        "uid": uid,
150        "device_id": device_id,
151        "web_sig": web_sig,
152        "broker_id": broker_id,
153    });
154
155    let uid_fp = uid_log_fingerprint(uid);
156    tracing::info!(
157        broker_id,
158        uid_fp = %uid_fp,
159        url = %url,
160        attribution = ?attribution,
161        "v1.4.93 G2: POST /authority/repull_auth_code (broker auth_code refresh)"
162    );
163
164    // 注意: 不打印 body (含 web_sig) — 走 redact_auth_body 才能 log,
165    // 这里只 info url + broker_id; 失败场景下走 error/warn 仍只透出 ret_type
166    let headers = super::http_client::auth_business_headers(client_type, device_id)?;
167    let resp: serde_json::Value = http
168        .post(&url)
169        .headers(headers)
170        .json(&body)
171        .send()
172        .await
173        .map_err(|e| FutuError::Network(std::io::Error::other(e.to_string())))?
174        .json()
175        .await
176        .map_err(|e| FutuError::Codec(format!("repull_auth_code: response not JSON: {e}")))?;
177
178    // 错误分支 (对齐 C++ ParseRepullAuthCodeResponse:3340-3358)
179    if let Some(err) = resp.get("error").and_then(|e| e.as_object()) {
180        let code = err.get("error_code").and_then(|v| v.as_i64()).unwrap_or(-1);
181        let msg = err
182            .get("error_msg")
183            .and_then(|v| v.as_str())
184            .unwrap_or("unknown");
185        if code != 0 {
186            tracing::warn!(
187                broker_id,
188                uid_fp = %uid_fp,
189                error_code = code,
190                error_msg = %msg,
191                no_valid_cid = code == ERROR_CODE_NO_VALID_CID,
192                "v1.4.93 G2: RepullAuthCode failed"
193            );
194            return Err(FutuError::ServerError {
195                ret_type: code as i32,
196                msg: format!("repull_auth_code broker_id={broker_id}: {msg}"),
197            });
198        }
199    }
200
201    let result = resp
202        .get("result")
203        .and_then(|r| r.as_object())
204        .ok_or_else(|| {
205            FutuError::Codec("repull_auth_code: missing result + missing error".into())
206        })?;
207
208    parse_repull_success_response(result, uid, broker_id)
209}
210
211fn repull_auth_code_url(attribution: UserAttribution) -> String {
212    // `auth_domain()` already returns a complete base URL with scheme. All
213    // other primary-auth call sites use it as-is; do not prepend another
214    // `https://`.
215    format!("{}{}", attribution.auth_domain(), REPULL_AUTH_CODE_PATH)
216}
217
218fn parse_repull_success_response(
219    result: &serde_json::Map<String, serde_json::Value>,
220    uid: u64,
221    broker_id: u32,
222) -> Result<BrokerAuthCode> {
223    // 对齐 C++ ParseRepullAuthCodeResponse:3325-3338 字段抽取 + 校验
224    let resp_uid = result.get("uid").and_then(|v| v.as_u64()).unwrap_or(0);
225    let resp_broker_id_raw = result
226        .get("broker_id")
227        .and_then(|v| v.as_u64())
228        .ok_or_else(|| FutuError::Codec("repull_auth_code: response broker_id invalid".into()))?;
229    let resp_broker_id = u32::try_from(resp_broker_id_raw).map_err(|_| {
230        FutuError::Codec(format!(
231            "repull_auth_code: response broker_id invalid (got {resp_broker_id_raw})"
232        ))
233    })?;
234    let auth_code = result
235        .get("auth_code")
236        .and_then(|v| v.as_str())
237        .unwrap_or("")
238        .to_string();
239    let invalid_time = result
240        .get("invalid_time")
241        .and_then(|v| v.as_u64())
242        .unwrap_or(0);
243
244    // C++ 校验 1: uid + broker_id 必须 match
245    if resp_uid != uid {
246        let expected_uid_fp = uid_log_fingerprint(uid);
247        let got_uid_fp = uid_log_fingerprint(resp_uid);
248        return Err(FutuError::Codec(format!(
249            "repull_auth_code: response uid mismatch (expected {expected_uid_fp}, \
250             got {got_uid_fp})"
251        )));
252    }
253    if resp_broker_id != broker_id {
254        return Err(FutuError::Codec(format!(
255            "repull_auth_code: response broker_id mismatch (expected {broker_id}, \
256             got {resp_broker_id})"
257        )));
258    }
259    // C++ 校验 2: auth_code 非空 + invalid_time 非 0
260    if auth_code.is_empty() || invalid_time == 0 {
261        return Err(FutuError::Codec(format!(
262            "repull_auth_code: empty auth_code or invalid_time (auth_code_len={}, \
263             invalid_time={invalid_time})",
264            auth_code.len()
265        )));
266    }
267
268    tracing::info!(
269        broker_id,
270        uid_fp = %uid_log_fingerprint(uid),
271        invalid_time,
272        auth_code_len = auth_code.len(),
273        "v1.4.93 G2: RepullAuthCode success — broker auth_code refreshed"
274    );
275
276    Ok(BrokerAuthCode {
277        broker_id,
278        auth_code,
279        invalid_time,
280    })
281}
282
283#[cfg(test)]
284mod tests;