Files
junhong_cmp_fiber/internal/gateway/readonly_guard.go
邹进 6266cf9d86
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m30s
feat: 网关只读卡名单,测试环境导入的生产卡只允许查询
- 新增 JUNHONG_GATEWAY_READONLY_ICCIDS:名单内的卡只放行查流量、卡状态、实名查询,
  停机、复机、限速、实名认证等写操作在网关出口本地拦截、不发请求,返回明确失败
- 未配置时不生效;测试环境部署脚本配置卡 89861590172420410612 用于流量采集验证

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:15:00 +09:00

74 lines
2.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gateway
import (
"encoding/json"
"strings"
"go.uber.org/zap"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
)
// readonlyAllowedPaths 是只读卡允许调用的网关接口:只查流量、卡状态与实名状态。
var readonlyAllowedPaths = map[string]struct{}{
"/flow-card/flow": {},
"/flow-card/status": {},
"/flow-card/realName": {},
}
// WithReadonlyCards 设置只读卡名单(逗号分隔的 ICCID,支持链式调用)。
// 名单里的卡只放行查询接口,停机、复机、限速、实名认证等写操作在本地拦截、不发请求;
// 用于把生产卡导入测试环境做流量采集验证,名单为空时不生效(生产不配置)。
func (c *Client) WithReadonlyCards(iccids string) *Client {
cards := map[string]struct{}{}
for _, iccid := range strings.Split(iccids, ",") {
if iccid = strings.ToUpper(strings.TrimSpace(iccid)); iccid != "" {
cards[iccid] = struct{}{}
}
}
c.readonlyCards = cards
if len(cards) > 0 && c.logger != nil {
c.logger.Warn("Gateway 只读卡名单已启用:名单内的卡只允许查询,写操作一律拦截", zap.Int("card_count", len(cards)))
}
return c
}
// rejectReadonlyWrite 判断本次请求是否为只读卡的写操作;是则记日志并返回明确失败(不是结果未知),不发请求。
func (c *Client) rejectReadonlyWrite(path string, params interface{}) error {
if len(c.readonlyCards) == 0 {
return nil
}
if _, ok := readonlyAllowedPaths[path]; ok {
return nil
}
cardNo := requestCardNo(params)
if _, blocked := c.readonlyCards[cardNo]; !blocked {
return nil
}
if c.logger != nil {
c.logger.Warn("Gateway 只读卡写操作已拦截,未发送请求",
zap.String("path", path), zap.String("card_no", cardNo), zap.String("metric", "gateway.readonly_card.blocked"))
}
return newGatewayError(constants.GatewayErrorUpstream, errors.New(errors.CodeGatewayError, "测试环境只读卡,已拦截写操作:"+path))
}
// requestCardNo 取请求里的卡号(cardNo 或 iccid 字段),取不到时返回空串。
func requestCardNo(params interface{}) string {
raw, err := json.Marshal(params)
if err != nil {
return ""
}
var fields struct {
CardNo string `json:"cardNo"`
ICCID string `json:"iccid"`
}
if err := json.Unmarshal(raw, &fields); err != nil {
return ""
}
if fields.CardNo != "" {
return strings.ToUpper(strings.TrimSpace(fields.CardNo))
}
return strings.ToUpper(strings.TrimSpace(fields.ICCID))
}