← Back to Pull requests

fix(wopan): apply browser user agent and refresh tokens before init #3222

Closed
unknown closed this pull request without merging on Oct 20, 2026 12:38 UTC
View on GitHub
unknown unknown commented on Oct 20, 2026 11:58 UTC
Author

<!--
PR title / PR 标题:

  • Use Conventional Commits: type(scope): summary

  • Allowed types: feat, docs, fix, style, refactor, chore

  • Scope is required by the current PR title check.

  • For breaking changes, add !: feat(driver)!: change auth flow

  • -->

    fix(wopan): apply browser user agent and refresh tokens before init

    Base: main ← Compare: fix/wopan-403-user-agent
    Commit: 57cd71c · Files changed: 3 (+249 / −9)
    Open PR: https://github.com/OpenListTeam/OpenList/pull/new/fix/wopan-403-user-agent

    Summary / 摘要

    联通云盘(WoPan)存储初始化失败,日志为
    failed get objs: failed to list objs: request failed with status: 403 Forbidden,
    只填 refresh token 时还会先报 failed init storage: crypto/aes: invalid key size 0。

    WoPan storages could not be initialized: every dispatcher request was answered
    with 403 Forbidden, and refresh-token-only configurations additionally failed
    with crypto/aes: invalid key size 0 before any request was even accepted.

    根因是驱动初始化阶段的两个缺陷:

    1. User-Agent 缺失:wopan-sdk-go 把浏览器 UA 存在私有字段里
    (WithUA/SetUA),只在 upload2C 上传时用 w.ua 显式写入请求头,
    其余 dispatcher 请求(QueryAllFiles、FamilyUserCurrentEncode 等)
    一路裸奔,最终由 resty 自动补成 go-resty/2.17.2 (...)。联通云盘边缘节点
    直接 403 掉非浏览器 UA。
    2. Token 初始化顺序错误:Init 先调 FamilyUserCurrentEncode() 再调
    InitData()。该请求体用 accessToken[:16] 做 AES 密钥加密,仅配 refresh
    token 时 access token 为空 → 密钥长度 0 → crypto/aes: invalid key size 0。

    <!--

  • List user-visible behavior changes.

  • List important implementation changes.

  • Mention config, storage, API, or compatibility changes if any.
  • 列出用户可感知的行为变化。

  • 列出重要实现变化。

  • 如涉及配置、存储、API 或兼容性变化,请明确说明。

  • -->

    User-visible behavior changes / 用户可感知的行为变化:

  • 联通云盘存储可以正常初始化、列出目录,不再报 403 Forbidden。

  • WoPan storages initialize and list again instead of failing with
    403 Forbidden.
  • 仅填 refresh token(不再必须同时填 access token)即可添加存储;access token

  • 为空或长度不足 16 时会先自动刷新,不再出现
    crypto/aes: invalid key size 0。
    A refresh token alone is enough to add the storage; a missing or too short
    access token is refreshed up front instead of failing with
    crypto/aes: invalid key size 0.
  • 配置项文案更新:refresh_token 不再标记为必填,两个 token 都增加了说明。

  • Field help text updated: refresh_token is no longer mandatory and both
    token fields describe the new behaviour.

    Important implementation changes / 重要实现变化:

  • Init 精简为「建 client + 注册 token 回调」,具体初始化移入

  • initClient(ctx)。
    Init now only builds the client and registers the token callback; the real
    initialization lives in initClient(ctx).
  • initClient 第一件事是 d.client.SetUserAgent(wopan.DefaultUA),保证后续所有

  • dispatcher 请求都带浏览器 UA。
    initClient starts with d.client.SetUserAgent(wopan.DefaultUA) so every
    dispatcher request carries the browser UA.
  • 新增 minAccessTokenLen = 16 常量(与 SDK 内部

  • Crypto.SetAccessToken 的校验一致)。access token 缺失/过短时先
    RefreshToken() 并校验刷新结果,然后才 InitData() → FamilyUserCurrentEncode()。
    Added minAccessTokenLen = 16 (mirrors the SDK's internal
    Crypto.SetAccessToken check). A missing or too short access token is
    refreshed and validated before InitData() and FamilyUserCurrentEncode().
  • 错误信息带阶段前缀(refresh access token: / initialize user data: /

  • query default family:),FamilyUserCurrentEncode 透传 ctx。
    Errors now carry a stage prefix, and FamilyUserCurrentEncode propagates
    ctx.
  • token 刷新回调拆为 setTokens + op.MustSaveDriverStorage,便于测试注入。

  • The refresh callback is split into setTokens plus the storage save so tests
    can inject it.
  • 未升级 wopan-sdk-go:v0.2.0/v0.2.2 的 SetUA 仍然只写字段

  • (client.SetUserAgent 才写 resty header),升级不能修掉 403,反而引入
    psToken 等 API 变更,因此保持在 v0.1.5 并在驱动侧修正。
    No SDK bump: SetUA in v0.2.0/v0.2.2 still only stores the value (only
    client.SetUserAgent writes the resty header), so upgrading would not fix the
    403 and would drag in unrelated API changes (psToken, ...).

  • This PR has breaking changes.

  • / 此 PR 包含破坏性变更。
  • This PR changes public API, config, storage format, or migration behavior.

  • / 此 PR 修改了公开 API、配置、存储格式或迁移行为。
  • This PR requires corresponding changes in related repositories.

  • / 此 PR 需要关联仓库同步修改。

    Related repository PRs / 关联仓库 PR:

  • OpenList-Frontend:

  • OpenList-Docs:
  • Related Issues / 关联 Issue

    Relates to #3218(同一个 403 Forbidden + crypto/aes: invalid key size 0 现象,
    该 issue 因模板勾选问题被机器人关闭,但日志症状与本 PR 修复的两条路径完全一致)
    Relates to #3218 (same 403 Forbidden + crypto/aes: invalid key size 0
    symptoms; the issue was auto-closed by the bot, but its log shows exactly the two
    failure paths fixed here).

    参考实现 / Reference: AlistGo/alist#9674
    (fix(wopan): initialize tokens and set dispatcher user agent).

    Root Cause / 根因分析

    1. dispatcher 请求缺少浏览器 UA → HTTP 403

    wopan-sdk-go@v0.1.5 内部:

    // client.go
    func Default() *WoClient { return New(WithUA(DefaultUA)) }
    func (w *WoClient) SetUA(ua string) { w.ua = ua }              // 只存字段
    func (w *WoClient) SetUserAgent(ua string) *WoClient {          // 才真正落到 resty
    	w.client.SetHeader("User-Agent", ua)
    	return w
    }
    
    // request.go —— dispatcher 请求只设置了 3 个 header
    req.SetHeaders(map[string]string{"Origin": ..., "Referer": ...})
    if w.accessToken != "" { req.SetHeader("Accesstoken", w.accessToken) }
    
    // upload.go —— 只有上传显式带上 UA
    SetHeaders(map[string]string{..., "User-Agent": w.ua})
    

    于是任一 dispatcher 请求都没有 UA,resty v2.17.2 在
    middleware.go:179 补上库自身的 UA:

    if IsStringEmpty(r.Header.Get(hdrUserAgentKey)) {
    	r.Header.Set(hdrUserAgentKey, hdrUserAgentValue) // go-resty/2.17.2 (...)
    }
    

    联通云盘边缘对这串 UA 直接返回 403,驱动侧只看到
    request failed with status: 403 Forbidden(res.IsError() 分支,甚至进不到
    业务错误码判断)。

    反证:同账号下上传一直正常(upload2C 显式写了浏览器 UA),只有

    列目录/初始化 403 —— 说明不是 token 过期,而是 UA 被判风控。

    2. 先请求后刷新 → crypto/aes: invalid key size 0

    // 旧 Init
    fml, err := d.client.FamilyUserCurrentEncode()  // ← 先请求
    d.defaultFamilyID = strconv.Itoa(fml.DefaultHomeId)
    return d.client.InitData()                      // ← 后才(必要时)刷新 token
    

    SDK 所有 wohome 请求体都用 accessToken[:16] 加密,且
    Crypto.SetAccessToken 在 len(token) < 16 时返回 ErrInvalidAccessToken
    (驱动层没检查这个返回值),accessKey 保持 nil:

    func AesEncrypt(bs, key, iv []byte) ([]byte, error) { ... aes.NewCipher(key) ... }
    // key 长度 0 → crypto/aes: invalid key size 0
    

    仅配 refresh token(旧 meta.go 里 refresh_token 是 required:"true",
    而 access token 是可选项)时必然命中。

    现象对照 / Symptom → Cause

    | 日志现象 / Log | 根因 / Cause |
    | --- | --- |
    | failed get objs: failed to list objs: request failed with status: 403 Forbidden | 缺少浏览器 UA(缺陷 1) |
    | failed init storage: crypto/aes: invalid key size 0 | access token 为空/过短,先请求后刷新(缺陷 2) |
    | 上传能成功、列目录 403 | upload2C 显式写 User-Agent: w.ua |
    | 两个 token 都填好仍然 403 | UA 与 token 无关,两个 token 都填只是绕过了缺陷 2 |

    Testing / 测试

    <!--
    Describe commands, platforms, and manual checks.
    If not tested, explain why.

    说明执行过的命令、测试平台和手动验证。
    如果未测试,请说明原因。
    -->

  • go test ./drivers/wopan/ -count=1(改动仅限该包,仓库其余包未涉及,未全量执行)

  • go test ./...

  • Manual test / 手动测试: 未使用真实账号验证(无可用的 token),需要在有账号的环境补一次

  • Not verified against a real account (no token available); a real-account
    run is still recommended.

    Automated checks run / 已执行的自动化检查:

    | Command / 命令 | Result / 结果 |
    | --- | --- |
    | go build ./... | OK |
    | go vet ./drivers/wopan/ | OK |
    | go test ./drivers/wopan/ -count=1 | PASS(6 子用例) |
    | gofmt -l | 无差异(仅 CRLF 行尾在 Windows 检出下被标记,与本次改动无关) |

    New tests / 新增测试 (drivers/wopan/driver_test.go):

  • TestInitClientCredentials:表驱动覆盖 6 种凭据组合

  • (仅 refresh / 短 access + refresh / 双 token / 仅 access /
    双空 / 仅短 access),断言:
    - 每个 dispatcher 请求的 User-Agent 必须等于 wopan.DefaultUA;
    - 需要刷新时 AppRefreshToken 必须是第一个请求;
    - 刷新后 AccessToken/RefreshToken 回写正确;
    - 凭据不合法时不发任何请求并返回错误;
    - defaultFamilyID 来自 FamilyUserCurrentEncode(42)。
  • 测试内的 mock transport 模拟真实边缘行为:UA 不是浏览器 UA 就返回

  • 403 Forbidden,因此能精确复现线上报错。

    回归验证 / Negative check:临时注释掉 d.client.SetUserAgent(wopan.DefaultUA)
    后重新运行,测试按预期失败,报错与用户反馈完全一致:

    === RUN   TestInitClientCredentials/both_tokens
        initClient returned error: initialize user data: request failed with status: 403 Forbidden
    --- FAIL: TestInitClientCredentials
    

    恢复该行后全部通过,说明测试确实锁住了 UA 回归。

    Manual verification steps / 手动验证步骤(建议在合并前执行一次):

    1. 用短信登录拿到 refresh_token(或同时提供 access_token),只填
    refresh_token 添加联通云盘存储。
    2. 期望:存储初始化成功、无 crypto/aes: invalid key size 0、根目录可列出。
    3. 期望:AccessToken 被刷新后回写进存储配置(重启后仍然可用)。
    4. 上传/下载各验证一次,确认 UA 修复没有影响 upload2C(该路径原本就带 UA)。

    Checklist / 检查清单

  • I have read CONTRIBUTING.

  • / 我已阅读 CONTRIBUTING。
  • I confirm this contribution follows the repository license, contribution policy, and code of conduct.

  • / 我确认此贡献符合仓库许可证、贡献规范和行为准则。
  • I have formatted the changed code with gofmt, go fmt, or prettier where applicable.

  • / 我已按适用情况使用 gofmt 格式化变更代码。
  • I have requested review from relevant maintainers or code owners where applicable.

  • / 我已在适用情况下请求相关维护者或代码所有者审查。

    AI Disclosure / AI 使用声明

  • This PR includes AI-assisted content.

  • / 此 PR 包含 AI 辅助内容。

    Tools used / 使用工具:

  • ChatGPT

  • Codex

  • GitHub Copilot

  • Claude

  • Gemini

  • Other (please specify) / 其他(请注明): CodeBuddy (DeepSeek-V4.1-Flash)
  • Usage scope / 使用范围:

  • Code generation / 代码生成

  • Refactoring / 重构

  • Documentation / 文档

  • Tests / 测试

  • Translation / 翻译

  • Review assistance / 审查辅助
  • I have reviewed and validated all AI-assisted content included in this PR.

  • / 我已审核并验证此 PR 中的所有 AI 辅助内容。
  • I have ensured that all AI-assisted commits include Co-Authored-By attribution.

  • / 我已确保所有 AI 辅助提交都包含 Co-Authored-By 归属信息。
  • I can reproduce all AI-assisted content included in this PR without any AI tools.

  • / 我可以在没有任何 AI 工具的情况下重现此 PR 中包含的内容。

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: elysia-best Review duration: 40m
    All Vouch review confidence checks passed
    Residual risk 0.30 = Change Risk (0.75) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.75 · 650 lines diff across 8 files
    0.75
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Sensitive Paths sensitive_paths
    0.075
    Real PR Conversation Timeline
    1 comments
    "Review active on #3222"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 75.2% (HIGH) · Higher = larger blast radius
    75.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 29.7% · Safe to merge
    29.7%