Skip to content

fix: extract token initialization into getToken method#397

Merged
qiuzhiqian merged 1 commit intodevelop/intranet-updatefrom
fix-token-empty
Apr 24, 2026
Merged

fix: extract token initialization into getToken method#397
qiuzhiqian merged 1 commit intodevelop/intranet-updatefrom
fix-token-empty

Conversation

@qiuzhiqian
Copy link
Copy Markdown

Ensure token is initialized before use by encapsulating the lazy initialization logic in a dedicated getToken method.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 24, 2026

CLA Assistant Lite bot:
提交邮箱中包含我们的合作伙伴,但您似乎并非合作伙伴的成员或对接人,请联系相关对接人将您添加至组织之中,或由其重新发起 Pull Request。
The commit email domain belongs to one of our partners, but it seems you are not yet a member of the current organization, please contact the contact person to add you to the organization or let them submit the Pull Request.

xml seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You can retrigger this bot by commenting recheck in this Pull Request

Ensure token is initialized before use by encapsulating the lazy
initialization logic in a dedicated getToken method.

Bug: https://pms.uniontech.com/bug-view-358591.html
@deepin-ci-robot
Copy link
Copy Markdown

deepin pr auto review

Git Diff 代码审查报告

整体评估

这段代码主要做了以下修改:

  1. 新增了一个 getToken() 方法,用于封装获取 Token 的逻辑
  2. 将多处直接使用 m.Token 的地方替换为调用 m.getToken()
  3. 在测试用例中添加了 Token 的初始化

代码质量与逻辑分析

优点

  1. 代码复用性提升:通过提取 getToken() 方法,避免了重复的 Token 判断和获取逻辑,符合 DRY (Don't Repeat Yourself) 原则。

  2. 封装性增强:将 Token 获取逻辑封装在一个方法中,使得未来对 Token 获取逻辑的修改更加集中和方便。

  3. 测试用例完善:在测试用例中添加了 Token 的初始化,确保测试的完整性。

潜在问题

  1. 线程安全问题

    • getToken() 方法没有考虑并发访问的情况。如果多个 goroutine 同时调用此方法,可能会导致 UpdateTokenConfigFile 被多次调用。
    • 建议:使用 sync.Once 或互斥锁来确保 UpdateTokenConfigFile 只被调用一次。
  2. 错误处理缺失

    • getToken() 方法没有返回错误,如果 UpdateTokenConfigFile 调用失败,调用者无法知道。
    • 建议:将返回类型改为 (string, error),并在调用处处理可能的错误。
  3. 安全性问题

    • 代码中有一个硬编码的 secret 常量:const secret = "DflXyFwTmaoGmbDkVj8uD62XGb01pkJn",这存在安全风险。
    • 建议:将敏感信息移至配置文件或环境变量中。
  4. 性能考虑

    • 每次调用 getToken() 都会进行 len(m.Token) == 0 的检查,虽然开销很小,但如果频繁调用可能会有轻微影响。
    • 建议:可以考虑在 UpdatePlatformManager 初始化时就获取 Token,而不是延迟加载。

改进建议

1. 解决线程安全问题

var tokenOnce sync.Once

func (m *UpdatePlatformManager) getToken() (string, error) {
    var err error
    tokenOnce.Do(func() {
        if len(m.Token) == 0 {
            m.Token, err = UpdateTokenConfigFile(m.config.IncludeDiskInfo, m.config.GetHardwareIdByHelper)
        }
    })
    return m.Token, err
}

2. 改进错误处理

func (m *UpdatePlatformManager) genVersionResponse() (*http.Response, error) {
    policyUrl := m.requestUrl + Urls[GetVersion].path
    client := &http.Client{
        Timeout: time.Duration(m.config.HttpTimeout) * time.Second,
    }
    request, err := http.NewRequest("GET", policyUrl, nil)
    if err != nil {
        return nil, fmt.Errorf("%v new request failed: %v ", GetVersion.string(), err.Error())
    }
    
    token, err := m.getToken()
    if err != nil {
        return nil, fmt.Errorf("failed to get token: %v", err)
    }
    
    request.Header.Set("X-Repo-Token", base64.RawStdEncoding.EncodeToString([]byte(token)))
    request.Header.Set("X-Packages", base64.RawStdEncoding.EncodeToString([]byte(getClientPackageInfo(m.config.ClientPackageName))))
    return client.Do(request)
}

3. 安全性改进

将硬编码的 secret 移至配置文件或环境变量:

// 从环境变量获取 secret
secret := os.Getenv("UPDATE_PLATFORM_SECRET")
if secret == "" {
    return nil, errors.New("UPDATE_PLATFORM_SECRET environment variable is not set")
}

4. 性能优化

考虑在 UpdatePlatformManager 初始化时就获取 Token:

func NewUpdatePlatformManager(config *Config) (*UpdatePlatformManager, error) {
    manager := &UpdatePlatformManager{
        config: config,
    }
    
    // 初始化时获取 Token
    token, err := UpdateTokenConfigFile(config.IncludeDiskInfo, config.GetHardwareIdByHelper)
    if err != nil {
        return nil, fmt.Errorf("failed to initialize token: %v", err)
    }
    manager.Token = token
    
    return manager, nil
}

总结

这次代码修改提高了代码的复用性和可维护性,但需要考虑线程安全、错误处理和安全性问题。建议按照上述建议进行改进,以提高代码的健壮性和安全性。

@deepin-ci-robot
Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: qiuzhiqian, zhaohuiw42

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@qiuzhiqian qiuzhiqian merged commit ffacf11 into develop/intranet-update Apr 24, 2026
23 of 29 checks passed
@qiuzhiqian qiuzhiqian deleted the fix-token-empty branch April 24, 2026 10:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants