Files
iotlcm/internal/logic/upstreamimpl/beixin_token_provider.go
T
MiFaZhan 96b1edff45 chore: 初始开源发布
iotlcm-upstream-chan:运营商上游通道适配服务(统一 /sim/* 协议)。

- 内联原私有依赖:yunze-public → internal/pub/(10 包 18 文件),
  yunze-pb/pb → internal/pb/(9 文件);Consul 注册改用官方
  gogf/gf/contrib/registry/consul/v2(API 兼容)
- Go module:yz-svr → git.5iot.com/iotlcm-public/iotlcm-upstream-chan
- 修复 mingqian 包测试:实现重构后 `adapter.operations` 字段已移除,
  测试断言按当前实现语义重写(不改产品行为)
- 凭据与内部标识脱敏:MySQL/Redis/Consul 凭据、私网与生产 IP、
  内网域名、真实手机号、注释里的真实 token/transid
- 移除内部资产:CI 触发器、生产通道种子 SQL、真实凭据测试资源文档
- Dockerfile 改用公共基础镜像,移除写死的 registry 凭据
- 补 Apache-2.0 LICENSE,重写 README,LF 行尾 + .gitattributes
2026-10-22 16:08:06 +08:00

150 lines
5.3 KiB
Go

package upstreamimpl
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
sharedtoken "git.5iot.com/iotlcm-public/iotlcm-upstream-chan/internal/token"
)
// beixinOneLinkTokenPath is the fallback used when Path is empty. On the
// template path this default is unreachable: parseSharedOneLinkConfig rejects
// an empty token.path before any provider is built, so Path always carries the
// value declared in temp_config. It only applies to direct construction
// (tests). The same shape exists in every shared-token provider.
const beixinOneLinkTokenPath = "/prod-api/open/api/oneLinkToken"
// beixinTokenTTL is the local validity window. The upstream returns only the
// token string and no expiry field, so the window is held locally; a token
// rejected earlier than this is recovered through RecoverToken's invalidation
// path instead of being trusted until the TTL elapses.
const beixinTokenTTL = time.Hour
// BeixinTokenConfig contains all values required by the Beixin (江苏倍信)
// shared-token protocol. BaseURL and Path come from temp_config
// token.baseUrl/token.path (with the per-channel tokenBaseUrl override
// applied by parseSharedOneLinkConfig); the credentials come from chan_config.
type BeixinTokenConfig struct {
BaseURL string
Path string
PwdKey string
ChannelNo string
Timeout time.Duration
}
// BeixinTokenProvider fetches a Beixin shared OneLink token.
//
// Wire contract (verified against the live endpoint on 2026-10-19):
//
// GET {baseUrl}{path}?pwdkey=<pwdKey>&c_no=<channelNo>
// → {"code":200,"msg":"请求成功","data":"<64 chars>"}
//
// The token is consumed by the standard OneLink business API
// (https://api.iot.10086.cn/v5/), so all /sim/* routes work unchanged.
type BeixinTokenProvider struct {
baseURL string
path string
pwdKey string
channelNo string
client *http.Client
}
type beixinTokenResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data json.RawMessage `json:"data"`
}
func NewBeixinTokenProvider(config BeixinTokenConfig) *BeixinTokenProvider {
timeout := config.Timeout
if timeout <= 0 {
timeout = defaultUpstreamHTTPTimeout
}
return &BeixinTokenProvider{
baseURL: strings.TrimRight(strings.TrimSpace(config.BaseURL), "/"),
path: normalizeProviderPath(config.Path, beixinOneLinkTokenPath),
pwdKey: config.PwdKey,
channelNo: strings.TrimSpace(config.ChannelNo),
client: &http.Client{Timeout: timeout},
}
}
func (p *BeixinTokenProvider) Fetch(ctx context.Context) (sharedtoken.OneLinkToken, error) {
if p == nil || p.client == nil {
return sharedtoken.OneLinkToken{}, fmt.Errorf("beixin token provider is not initialized")
}
if p.baseURL == "" || strings.TrimSpace(p.pwdKey) == "" || p.channelNo == "" {
return sharedtoken.OneLinkToken{}, fmt.Errorf("beixin baseUrl, pwdKey and channelNo are required")
}
endpoint, err := url.Parse(joinProviderURL(p.baseURL, p.path))
if err != nil {
return sharedtoken.OneLinkToken{}, fmt.Errorf("parse beixin token URL: %w", err)
}
query := endpoint.Query()
query.Set("pwdkey", p.pwdKey)
query.Set("c_no", p.channelNo)
endpoint.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
return sharedtoken.OneLinkToken{}, fmt.Errorf("create beixin token request: %w", err)
}
req.Header.Set("Accept", "application/json")
resp, err := p.client.Do(req)
if err != nil {
return sharedtoken.OneLinkToken{}, fmt.Errorf("request beixin token: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 4*1024*1024+1))
if err != nil {
return sharedtoken.OneLinkToken{}, fmt.Errorf("read beixin token response: %w", err)
}
if len(body) > 4*1024*1024 {
return sharedtoken.OneLinkToken{}, fmt.Errorf("beixin token response is too large")
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return sharedtoken.OneLinkToken{}, fmt.Errorf("beixin token HTTP status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var output beixinTokenResponse
if err := json.Unmarshal(body, &output); err != nil {
return sharedtoken.OneLinkToken{}, fmt.Errorf("decode beixin token response: %w", err)
}
if output.Code != http.StatusOK {
return sharedtoken.OneLinkToken{}, fmt.Errorf("beixin token failed: code=%d, message=%s", output.Code, output.Msg)
}
// data is a bare JSON string, not an object.
var value string
if err := json.Unmarshal(output.Data, &value); err != nil {
return sharedtoken.OneLinkToken{}, fmt.Errorf("decode beixin shared token: %w", err)
}
value = strings.TrimSpace(value)
if value == "" {
return sharedtoken.OneLinkToken{}, fmt.Errorf("beixin shared token is empty")
}
now := time.Now()
return sharedtoken.OneLinkToken{Value: value, CreatedAt: now, ExpiresAt: now.Add(beixinTokenTTL)}, nil
}
func (p *BeixinTokenProvider) FetchToken(ctx context.Context, _ string) (sharedtoken.OneLinkToken, error) {
return p.Fetch(ctx)
}
// beixinFetcher adapts BeixinTokenProvider to the shared token TokenFetcher
// contract, mirroring tengyuFetcher.
type beixinFetcher struct{ provider *BeixinTokenProvider }
func (f beixinFetcher) FetchToken(ctx context.Context, _ string) (sharedtoken.OneLinkToken, error) {
return f.provider.Fetch(ctx)
}