Skip to main content

futu_auth/
scope.rs

1//! Scope: 能力分组
2
3use std::fmt;
4use std::str::FromStr;
5
6use futu_core::proto_id;
7use serde::{Deserialize, Serialize};
8
9/// API Key 能力分组
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(try_from = "String", into = "String")]
12#[non_exhaustive]
13pub enum Scope {
14    /// 行情只读(11 个工具)
15    QotRead,
16    /// 账户只读(5 个工具)
17    AccRead,
18    /// 模拟交易写
19    TradeSimulate,
20    /// 真实交易写
21    TradeReal,
22    /// 允许自动 unlock_trade(从 keychain 读密码)
23    TradeUnlock,
24    /// v1.4.32+ daemon 管理 (`/api/admin/status|reload|shutdown`)。
25    /// 权限危险,只给运维 / 监控 key;LLM key 永远不要加这个。
26    Admin,
27    /// v1.4.90 P1-A: trade 类 super-scope。**仅在 REST middleware
28    /// `scope_for_path` 用作"需要任意 trade* scope"的占位需求**:持有
29    /// [`Scope::TradeReal`] / [`Scope::TradeSimulate`] / [`Scope::TradeUnlock`]
30    /// 任一即满足。**不应**写入 keys.json(KeyRecord.scopes 里出现
31    /// `Scope::Trade` 没意义,等价于不分 sim/real/unlock 的旧式权限)。
32    /// env 是 sim 还是 real 由 handler 层用 KeyRecord 真实 scopes 二次校验。
33    Trade,
34    /// v1.4.106 codex 0542 F1 [P2 SECURITY]: `/metrics` 端点 scope-gated 的
35    /// 专用 scope. default secure — 不再像 v1.4.105 之前那样无 auth 暴露
36    /// `key_id` 标签 (= API key id 明文 cardinality enumeration channel,
37    /// 任意本机 process / agent skill 都能 fingerprint).
38    ///
39    /// **行为**:
40    /// - 持 `MetricsRead` 的 key → `/metrics` 通过, `key_id=` label 仍 redact
41    ///   为 `kh_<8hex>` (短 SHA256 hash, 反查 key id 需要离线 dictionary 攻击)
42    /// - 不持 `MetricsRead` → 401 (legacy 模式) 或 403
43    /// - **opt-out**: 老用户 dashboard 依赖明文 key_id 时设
44    ///   `FUTU_METRICS_PUBLIC=1` 环境变量回退 v1.4.105 行为 (无 auth + 明文
45    ///   key_id). 此为 backward-compat 边界 trade-off — secure default + 明示
46    ///   opt-out, 而非 opt-in.
47    ///
48    /// 与 [`Scope::Admin`] 区别: Admin 含 mutating endpoint (shutdown/reload),
49    /// MetricsRead 仅 read-only Prometheus 抓取. dashboard / Prometheus
50    /// scraper 应持 MetricsRead 而不是 Admin.
51    MetricsRead,
52}
53
54impl Scope {
55    pub const ALL: &'static [Scope] = &[
56        Scope::QotRead,
57        Scope::AccRead,
58        Scope::TradeSimulate,
59        Scope::TradeReal,
60        Scope::TradeUnlock,
61        Scope::Admin,
62        Scope::MetricsRead,
63    ];
64
65    #[must_use]
66    pub fn as_str(&self) -> &'static str {
67        match self {
68            Scope::QotRead => "qot:read",
69            Scope::AccRead => "acc:read",
70            Scope::TradeSimulate => "trade:simulate",
71            Scope::TradeReal => "trade:real",
72            Scope::TradeUnlock => "trade:unlock",
73            Scope::Admin => "admin",
74            Scope::Trade => "trade",
75            Scope::MetricsRead => "metrics:read",
76        }
77    }
78
79    /// v1.4.90 P1-A: super-scope `Scope::Trade` 的成员集合。REST
80    /// middleware 在 mutating trade endpoint 的需求侧用 `Scope::Trade`
81    /// 占位,持有任一成员即视为满足;handler 层再用真实 scopes
82    /// 二次校验 env (sim/real/unlock).
83    #[must_use]
84    pub fn trade_super_members() -> &'static [Scope] {
85        &[Scope::TradeReal, Scope::TradeSimulate, Scope::TradeUnlock]
86    }
87}
88
89impl fmt::Display for Scope {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str(self.as_str())
92    }
93}
94
95#[derive(Debug, thiserror::Error)]
96#[error(
97    "unknown scope {0:?} (valid: qot:read, acc:read, trade:simulate, trade:real, trade:unlock, admin, metrics:read)"
98)]
99pub struct ScopeParseError(pub String);
100
101impl FromStr for Scope {
102    type Err = ScopeParseError;
103
104    fn from_str(s: &str) -> Result<Self, Self::Err> {
105        match s {
106            "qot:read" => Ok(Scope::QotRead),
107            "acc:read" => Ok(Scope::AccRead),
108            "trade:simulate" => Ok(Scope::TradeSimulate),
109            "trade:real" => Ok(Scope::TradeReal),
110            "trade:unlock" => Ok(Scope::TradeUnlock),
111            "admin" => Ok(Scope::Admin),
112            // 注意:`"trade"` 仅作为 super-scope 内部占位 (Scope::Trade),
113            // 不允许从 keys.json / CLI --scopes 解析,避免用户误以为
114            // bare trade 会授予 trade:real / trade:simulate / trade:unlock。
115            // v1.4.106 codex 0542 F1 [P2 SECURITY]: /metrics 端点专用 scope.
116            "metrics:read" => Ok(Scope::MetricsRead),
117            other => Err(ScopeParseError(other.to_string())),
118        }
119    }
120}
121
122impl TryFrom<String> for Scope {
123    type Error = ScopeParseError;
124    fn try_from(value: String) -> Result<Self, Self::Error> {
125        value.parse()
126    }
127}
128
129impl From<Scope> for String {
130    fn from(s: Scope) -> String {
131        s.as_str().to_string()
132    }
133}
134
135/// Futu API protocol id → 所需 scope 的**通用映射**
136///
137/// gRPC 和核心 WS 都用这个函数做 scope 检查。proto_id 常量定义在 futu-core
138/// (circular dep 顾虑下这里手动枚举);新增 proto 时必须同步更新这里的 match
139/// 分支,否则落到 catch-all `TradeReal` 被拒(fail-closed)。
140///
141/// **v1.4.104 codex round 1 F4 (P2) fix**: 显式 trade/acc protos 用
142/// [`SCOPED_TRADE_REAL_PROTOS`] / [`SCOPED_TRADE_UNLOCK_PROTOS`] /
143/// [`SCOPED_ACC_READ_PROTOS`] 暴露给 invariant test, 让
144/// `body_aware::build_check_ctxs` + `response_filter::FilterRegistry` 共同
145/// 覆盖. 加新 scoped proto 时:
146/// 1. match 分支加 → 让 scope check 知道新 proto
147/// 2. 把 proto_id 加到对应的 `SCOPED_*_PROTOS` const list (机械 enumeration)
148/// 3. 其中 一处 (body_aware OR response_filter OR EXPLICIT_NO_ACC_ID_PROTOS)
149///    必须 cover, 否则 cross_surface_invariants test 挂.
150///
151/// | proto_id 范围 | 所需 scope |
152/// |---|---|
153/// | 1xxx 系统(InitConnect / GetGlobalState / KeepAlive / …) | 无(放行) |
154/// | 3xxx 行情(含 push updates) | `qot:read` |
155/// | 2005 UnlockTrade | `trade:unlock`(v1.4.104 codex F1 P1 fix) |
156/// | 2202 PlaceOrder / 2205 ModifyOrder / 2227 PlaceComboOrder / 2237 ReconfirmOrder | `trade:real` |
157/// | 2xxx 账户只读(AccList / Funds / Positions / Orders / Deals / 费率 / push) | `acc:read` |
158/// | 其他 | catch-all `trade:real`(fail-closed) |
159pub fn scope_for_proto_id(proto_id: u32) -> Option<Scope> {
160    match proto_id {
161        // v1.4.110 GetUsedQuota / v1.4.98 T2-8 GET_TOKEN_STATE 落在 1xxx
162        // 范围, 但有明确业务权限语义. 单独前置, 避免被下面
163        // 1000..=1999 => None 兜住.
164        1010 => Some(Scope::QotRead),
165        // NN+MM token 状态查询, unlock-trade 失败时第一线诊断.
166        // 否则被下面 1000..=1999 => None 兜住.
167        1326 => Some(Scope::AccRead),
168
169        // 1xxx 系统 / 连接管理:InitConnect / GlobalState / KeepAlive / UserInfo ...
170        1000..=1999 => None,
171
172        // 3xxx 全部行情(请求 + push 全挂 qot:read)
173        3000..=3999 => Some(Scope::QotRead),
174
175        // v1.4.115 financial / IPO calendar: mobile-driven read-only quote
176        // endpoints live outside the legacy 3xxx quote range, so they need
177        // explicit QotRead coverage before the 2xxx trade/account branches.
178        20025 | 20426 => Some(Scope::QotRead),
179
180        // 2005 UnlockTrade —— v1.4.104 codex round 1 F1 (P1) fix:
181        // 之前 mapping 是 TradeReal (推理 "未解锁不能下单, 视同 trade:real"
182        // 是错的). UnlockTrade 是独立 scope:caller 持 trade:unlock 才能解锁,
183        // 不应让 trade:real 通过. v1.4.103 codex F5.3 已让 MCP futu_unlock_trade
184        // 走 trade:unlock, 但 gRPC/raw WS 直调 proto 2005 时仍走 TradeReal —
185        // narrow Bearer (trade:real only, 无 trade:unlock) 可绕过 unlock scope.
186        // v1.4.104 阶段 7-5 改 MCP futu_unlock_trade 走 caller-specific
187        // pipeline (TradeUnlock check), 但 proto 2005 mapping 还是 TradeReal —
188        // codex round 1 F1 抓出 silent gap. 现统一改 TradeUnlock 关闭 4 surface
189        // 一致.
190        2005 => Some(Scope::TradeUnlock),
191
192        // 2202 PlaceOrder / 2205 ModifyOrder / 2227 PlaceComboOrder / 2237 ReconfirmOrder
193        2202 | 2205 | 2227 | 2237 => Some(Scope::TradeReal),
194
195        // 2xxx 账户只读:list / funds / positions / orders / deals / push / 费率
196        2001
197        | 2008
198        | proto_id::TRD_UNSUB_ACC_PUSH_LOCAL
199        | 2101
200        | 2102
201        | 2111
202        | 2112
203        | 2201
204        | 2208
205        | 2211
206        | 2218
207        | 2221
208        | 2222
209        | 2223
210        | 2225
211        | 2226
212        | 2240 => Some(Scope::AccRead),
213
214        // v1.4.94 / v1.4.95 Tier M (mobile-driven extensions, 22701-22710):
215        // 全 only-read 性质 (账户资金 / 业务分组 / margin / 合规 / 债券 holdings) →
216        // acc:read scope 统一. 不显式覆盖会 fall-through 到 TradeReal,
217        // 让 acc:read-only 的 LLM agent 调不到这些 endpoint.
218        //
219        // | proto_id | endpoint                  | 含义              |
220        // |----------|---------------------------|-------------------|
221        // | 22701    | TRD_GET_CASH_LOG          | v1.4.94 M1        |
222        // | 22702    | TRD_GET_CASH_DETAIL       | v1.4.94 M1        |
223        // | 22703    | TRD_GET_BIZ_GROUP         | v1.4.94 M1        |
224        // | 22704    | TRD_GET_MARGIN_INFO       | v1.4.95 U2-D      |
225        // | 22705    | TRD_GET_ACCOUNT_FLAG      | v1.4.95 U2-A      |
226        // | 22706    | TRD_GET_BOND_TOTAL_ASSET  | v1.4.95 U2-B      |
227        // | 22707    | TRD_GET_BOND_SINGLE_ASSET | v1.4.95 U2-B      |
228        // | 22708    | TRD_GET_BOND_POSITION_LIST| v1.4.95 U2-B      |
229        // | 22709    | TRD_GET_BOND_ANSWER_STATE | v1.4.95 U2-B      |
230        // | 22710    | TRD_GET_BOND_TRADE_REMIND | v1.4.95 U2-B      |
231        22701..=22710 => Some(Scope::AccRead),
232
233        // v1.4.98 T2-* (mobile-source-audit Phase 2): quote 类 read-only endpoint.
234        // - 6503 QOT_GET_SPREAD_TABLE: 摆盘步长
235        // - 20231 QOT_GET_RISK_FREE_RATE: 无风险利率 (期权定价)
236        // - 6365 / 6366 QOT_GET_TICKER_STATISTIC: 逐笔统计 + push
237        // (cmd 1326 GET_TOKEN_STATE 已前置 acc:read, 避免 1xxx None 兜底)
238        6503 | 6365 | 6366 | 20231 => Some(Scope::QotRead),
239
240        // 未覆盖 → fail-closed,统一拒(返回 TradeReal 让上游 check_scope 比对最严格)
241        _ => Some(Scope::TradeReal),
242    }
243}
244
245// ─────────────────────────────────────────────────────────────────────────────
246// v1.4.104 codex round 1 F4 (P2) fix: scoped proto_id 机械枚举
247//
248// 让 `futu-auth-pipeline::body_aware` / `response_filter` / 显式 exception
249// list 通过 `coverage_invariant` 测试**机械**对齐 — 加新 scoped proto 时
250// 漏一处必挂. 与 v1.4.103/104 之前 hand-maintained covered vec 不同, 现
251// 不再依赖人记忆.
252// ─────────────────────────────────────────────────────────────────────────────
253
254/// 显式 enumerate 所有需要 acc_id 白名单或响应 filter 的 trade write proto_id.
255/// `body_aware::build_check_ctxs` 必须 decode 这些 proto.
256pub const SCOPED_TRADE_REAL_PROTOS: &[u32] = &[
257    2202, // TRD_PLACE_ORDER
258    2205, // TRD_MODIFY_ORDER
259    2227, // TRD_PLACE_COMBO_ORDER
260    2237, // TRD_RECONFIRM_ORDER
261];
262
263/// 显式 enumerate trade unlock proto_id (caller-specific TradeUnlock scope).
264/// v1.4.104 codex F1 (P1) 加.
265pub const SCOPED_TRADE_UNLOCK_PROTOS: &[u32] = &[
266    2005, // TRD_UNLOCK_TRADE
267];
268
269/// 显式 enumerate acc:read proto_id. 大多数走 `body_aware` decode acc_id
270/// whitelist. 例外见 [`EXPLICIT_NO_ACC_ID_PROTOS`].
271pub const SCOPED_ACC_READ_PROTOS: &[u32] = &[
272    1326,                               // GET_TOKEN_STATE — 无 acc_id, 走 explicit exception
273    2001,                               // TRD_GET_ACC_LIST — request 无 acc_id, 走 response-filter
274    2008,                               // TRD_SUB_ACC_PUSH (multi acc_id_list)
275    proto_id::TRD_UNSUB_ACC_PUSH_LOCAL, // Rust-daemon local public unsub (multi acc_id_list)
276    2101,
277    2102,
278    2111,
279    2112, // funds / positions / max_trd_qtys / combo_max_trd_qtys
280    2201,
281    2208,
282    2211,
283    2218, // order list / order_update push / fill list / fill_update push
284    2221,
285    2222, // history orders / history fills
286    2223,
287    2225,
288    2226, // margin ratio / order fee / flow summary
289    2240, // notify push
290    // Tier M (v1.4.94/95)
291    22701,
292    22702,
293    22703, // cash log / detail / biz group
294    22704, // margin info
295    22705, // account flag
296    22706,
297    22707,
298    22708,
299    22709,
300    22710, // bond × 5
301];
302
303/// **v1.4.106 ζ28 redo (codex 0532 F4 P3)**: typed coverage exception kind
304/// — 替代无类型 `EXPLICIT_NO_BODY_AWARE_PROTOS` 数组. 每个 exception 必须
305/// 显式分类, 让 "为什么这个 proto 不走 body_aware" 的意图保留在代码里
306/// (而非靠注释推).
307///
308/// 4 个 variant 涵盖所有 "非 body-aware" 场景:
309///
310/// - [`Self::ResponseFiltered`] — request 无 acc_id, 但 response 含 acc_list[]
311///   走 [`futu_auth_pipeline::FilterRegistry`] (e.g. 2001 TRD_GET_ACC_LIST).
312/// - [`Self::PushOnly`] — push event 不是 request, 无 request-side body
313///   (e.g. 2208 TRD_UPDATE_ORDER / 2218 TRD_UPDATE_ORDER_FILL / 2240 TRD_NOTIFY).
314///   pipeline 不应 dispatch push proto 作 request, 但 scope check 仍跑.
315/// - [`Self::MetaNoAccount`] — meta query 无 acc_id 概念 (e.g. 1326
316///   GET_TOKEN_STATE NN/MM token 状态).
317/// - [`Self::InternalOnly`] — daemon-internal proto_id (高位 0x8000_0000 bit),
318///   不应从公开 surface 进入 (gRPC / raw WS / raw TCP). v1.4.106 codex 0532 F3
319///   public surface 显式 reject (见 [`is_internal_proto_id`]).
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321#[non_exhaustive]
322pub enum CoverageException {
323    ResponseFiltered,
324    PushOnly,
325    MetaNoAccount,
326    InternalOnly,
327}
328
329/// `(proto_id, CoverageException)` 显式分类表 — v1.4.106 ζ28 替代无类型
330/// `EXPLICIT_NO_BODY_AWARE_PROTOS`.
331///
332/// 每个 entry 在 invariant test 强制 match 某个 variant, 不允许 hand-roll
333/// "我加进去就行" 漏类型.
334pub const COVERAGE_EXCEPTIONS: &[(u32, CoverageException)] = &[
335    // ResponseFiltered — request 无 acc_id, response s2c.acc_list[] 走 FilterRegistry
336    (2001, CoverageException::ResponseFiltered),
337    // PushOnly — push event 不是 request
338    (2208, CoverageException::PushOnly),
339    (2218, CoverageException::PushOnly),
340    (2240, CoverageException::PushOnly),
341    // MetaNoAccount — meta query 无 acc_id 概念
342    (1326, CoverageException::MetaNoAccount),
343];
344
345/// 列出本 daemon 所有 proto_id → exception 映射表的 proto_id 集合.
346/// 与 [`COVERAGE_EXCEPTIONS`] 同步 (v1.4.106 ζ28 起 source-of-truth 是
347/// `COVERAGE_EXCEPTIONS`, 此 const 仅作 backward compat alias).
348///
349/// **保留供 backward compat**: `body_aware::extract_coverage` 用此 set
350/// 判 NoAccIdConcept 还是 NotRegistered. 加新 exception 走
351/// [`COVERAGE_EXCEPTIONS`] 自动反映在此.
352pub const EXPLICIT_NO_BODY_AWARE_PROTOS: &[u32] = &[
353    1326, // GET_TOKEN_STATE — meta query (NN/MM token state, 无 acc_id)
354    2001, // TRD_GET_ACC_LIST — 走 response-side filter (FilterRegistry)
355    2208, // TRD_UPDATE_ORDER push — 不是 request, 无 body_aware
356    2218, // TRD_UPDATE_ORDER_FILL push
357    2240, // TRD_NOTIFY push
358];
359
360/// **v1.4.106 ζ28 redo (codex 0532 F3 P2)**: 判一个 proto_id 是否是
361/// daemon-internal (高位 `0x8000_0000` bit set).
362///
363/// daemon-internal proto_id (e.g. `TRD_UNSUB_ACC_PUSH_INTERNAL = 0x8000_0000 |
364/// 2008` v1.4.102 codex 44 F1 fix) **绝不应**从公开 surface (gRPC / raw WS /
365/// raw TCP) 进入 — 仅 REST `/api/unsub-acc-push` handler 内部合成给 router.
366///
367/// 公开 surface 看到此 bit set 立即 reject (`Forbidden` 等价 wire error)
368/// 防探测 daemon 内部 routing.
369#[must_use]
370pub fn is_internal_proto_id(proto_id: u32) -> bool {
371    (proto_id & 0x8000_0000) != 0
372}
373
374#[cfg(test)]
375mod tests;