mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-11-16 23:04:24 +08:00
fix(i18n): use English runtime text and localize system UI
This commit is contained in:
@@ -32,32 +32,32 @@ func CompileRuleGraph(graph RuleGraph) (RuntimeRuleGraph, error) {
|
||||
for _, node := range graph.Nodes {
|
||||
config, err := compileRuleNodeConfig(node)
|
||||
if err != nil {
|
||||
return RuntimeRuleGraph{}, fmt.Errorf("节点 %s 的配置无法编译: %w", node.ID, err)
|
||||
return RuntimeRuleGraph{}, fmt.Errorf("unable to compile configuration for node %s: %w", node.ID, err)
|
||||
}
|
||||
if node.Type == RuleNodeStart {
|
||||
if runtime.Entry != "" {
|
||||
return RuntimeRuleGraph{}, errors.New("规则图包含多个开始节点")
|
||||
return RuntimeRuleGraph{}, errors.New("rule graph contains multiple start nodes")
|
||||
}
|
||||
runtime.Entry = node.ID
|
||||
}
|
||||
runtime.Nodes[node.ID] = RuntimeRuleNode{Type: node.Type, Config: config}
|
||||
}
|
||||
if runtime.Entry == "" {
|
||||
return RuntimeRuleGraph{}, errors.New("规则图缺少开始节点")
|
||||
return RuntimeRuleGraph{}, errors.New("rule graph is missing a start node")
|
||||
}
|
||||
for _, edge := range graph.Edges {
|
||||
node, ok := runtime.Nodes[edge.Source]
|
||||
if !ok {
|
||||
return RuntimeRuleGraph{}, fmt.Errorf("边 %s 的源节点 %s 不存在", edge.ID, edge.Source)
|
||||
return RuntimeRuleGraph{}, fmt.Errorf("edge %s references missing source node %s", edge.ID, edge.Source)
|
||||
}
|
||||
if _, ok := runtime.Nodes[edge.Target]; !ok {
|
||||
return RuntimeRuleGraph{}, fmt.Errorf("边 %s 的目标节点 %s 不存在", edge.ID, edge.Target)
|
||||
return RuntimeRuleGraph{}, fmt.Errorf("edge %s references missing target node %s", edge.ID, edge.Target)
|
||||
}
|
||||
if node.Next == nil {
|
||||
node.Next = make(map[string]string)
|
||||
}
|
||||
if _, exists := node.Next[edge.SourceHandle]; exists {
|
||||
return RuntimeRuleGraph{}, fmt.Errorf("节点 %s 的 %s 出口连接了多个目标", edge.Source, edge.SourceHandle)
|
||||
return RuntimeRuleGraph{}, fmt.Errorf("node %s output %s is connected to multiple targets", edge.Source, edge.SourceHandle)
|
||||
}
|
||||
node.Next[edge.SourceHandle] = edge.Target
|
||||
runtime.Nodes[edge.Source] = node
|
||||
@@ -109,7 +109,7 @@ func compileRuleNodeConfig(node RuleNode) (any, error) {
|
||||
var config BlockNodeConfig
|
||||
return config, decodeStrictConfig(node.Config, &config)
|
||||
default:
|
||||
return nil, fmt.Errorf("未知节点类型 %s", node.Type)
|
||||
return nil, fmt.Errorf("unknown node type %s", node.Type)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ func ValidateRuleGraph(ctx context.Context, graph RuleGraph, ipGroupExists func(
|
||||
return err
|
||||
}
|
||||
if hasRuleGraphCycle(nodes, outgoing, incoming) {
|
||||
return errors.New("规则图不能包含循环")
|
||||
return errors.New("rule graph must not contain cycles")
|
||||
}
|
||||
if err := validateRequiredHandles(graph.Nodes, handleTargets); err != nil {
|
||||
return err
|
||||
@@ -57,18 +57,18 @@ func ValidateRuleGraph(ctx context.Context, graph RuleGraph, ipGroupExists func(
|
||||
|
||||
func validateRuleGraphLimits(graph RuleGraph) error {
|
||||
if graph.SchemaVersion != RuleGraphSchemaVersion {
|
||||
return fmt.Errorf("规则图 schema_version 必须为 %d", RuleGraphSchemaVersion)
|
||||
return fmt.Errorf("rule graph schema_version must be %d", RuleGraphSchemaVersion)
|
||||
}
|
||||
if len(graph.Nodes) > maxRuleGraphNodes {
|
||||
return fmt.Errorf("规则图节点数不能超过 %d", maxRuleGraphNodes)
|
||||
return fmt.Errorf("rule graph must not contain more than %d nodes", maxRuleGraphNodes)
|
||||
}
|
||||
if len(graph.Edges) > maxRuleGraphEdges {
|
||||
return fmt.Errorf("规则图边数不能超过 %d", maxRuleGraphEdges)
|
||||
return fmt.Errorf("rule graph must not contain more than %d edges", maxRuleGraphEdges)
|
||||
}
|
||||
if raw, err := json.Marshal(graph); err != nil {
|
||||
return fmt.Errorf("规则图无法序列化: %w", err)
|
||||
return fmt.Errorf("unable to serialize rule graph: %w", err)
|
||||
} else if len(raw) > maxRuleGraphBytes {
|
||||
return errors.New("规则图大小不能超过 256 KiB")
|
||||
return errors.New("rule graph must not exceed 256 KiB")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -78,10 +78,10 @@ func validateRuleGraphNodes(ctx context.Context, graphNodes []RuleNode, ipGroupE
|
||||
startCount, allowCount, startID := 0, 0, ""
|
||||
for _, node := range graphNodes {
|
||||
if strings.TrimSpace(node.ID) == "" {
|
||||
return nil, "", errors.New("节点 ID 不能为空")
|
||||
return nil, "", errors.New("node ID must not be empty")
|
||||
}
|
||||
if _, exists := nodes[node.ID]; exists {
|
||||
return nil, "", fmt.Errorf("节点 ID %s 重复", node.ID)
|
||||
return nil, "", fmt.Errorf("duplicate node ID %s", node.ID)
|
||||
}
|
||||
nodes[node.ID] = node
|
||||
switch node.Type {
|
||||
@@ -92,17 +92,17 @@ func validateRuleGraphNodes(ctx context.Context, graphNodes []RuleNode, ipGroupE
|
||||
allowCount++
|
||||
case RuleNodeBlock, RuleNodeIPMatch, RuleNodeGeoMatch, RuleNodePoW, RuleNodeUACheck, RuleNodeSecurityCheck:
|
||||
default:
|
||||
return nil, "", fmt.Errorf("节点 %s 的类型 %s 未知", node.ID, node.Type)
|
||||
return nil, "", fmt.Errorf("node %s has unknown type %s", node.ID, node.Type)
|
||||
}
|
||||
if err := validateRuleNodeConfig(ctx, node, ipGroupExists); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
if startCount != 1 {
|
||||
return nil, "", errors.New("规则图必须恰好包含一个开始节点")
|
||||
return nil, "", errors.New("rule graph must contain exactly one start node")
|
||||
}
|
||||
if allowCount != 1 {
|
||||
return nil, "", errors.New("规则图必须恰好包含一个通过节点")
|
||||
return nil, "", errors.New("rule graph must contain exactly one allow node")
|
||||
}
|
||||
return nodes, startID, nil
|
||||
}
|
||||
@@ -114,26 +114,26 @@ func validateRuleGraphEdges(nodes map[string]RuleNode, graphEdges []RuleEdge) (m
|
||||
handleTargets := make(map[string]int)
|
||||
for _, edge := range graphEdges {
|
||||
if strings.TrimSpace(edge.ID) == "" {
|
||||
return nil, nil, nil, errors.New("边 ID 不能为空")
|
||||
return nil, nil, nil, errors.New("edge ID must not be empty")
|
||||
}
|
||||
if _, exists := edgeIDs[edge.ID]; exists {
|
||||
return nil, nil, nil, fmt.Errorf("边 ID %s 重复", edge.ID)
|
||||
return nil, nil, nil, fmt.Errorf("duplicate edge ID %s", edge.ID)
|
||||
}
|
||||
edgeIDs[edge.ID] = struct{}{}
|
||||
source, ok := nodes[edge.Source]
|
||||
if !ok {
|
||||
return nil, nil, nil, fmt.Errorf("边 %s 的源节点 %s 不存在", edge.ID, edge.Source)
|
||||
return nil, nil, nil, fmt.Errorf("edge %s references missing source node %s", edge.ID, edge.Source)
|
||||
}
|
||||
if _, ok := nodes[edge.Target]; !ok {
|
||||
return nil, nil, nil, fmt.Errorf("边 %s 的目标节点 %s 不存在", edge.ID, edge.Target)
|
||||
return nil, nil, nil, fmt.Errorf("edge %s references missing target node %s", edge.ID, edge.Target)
|
||||
}
|
||||
if !validSourceHandle(source.Type, edge.SourceHandle) {
|
||||
return nil, nil, nil, fmt.Errorf("边 %s 的源端口 %s 不适用于节点 %s", edge.ID, edge.SourceHandle, edge.Source)
|
||||
return nil, nil, nil, fmt.Errorf("edge %s source port %s is not valid for node %s", edge.ID, edge.SourceHandle, edge.Source)
|
||||
}
|
||||
key := edge.Source + "\x00" + edge.SourceHandle
|
||||
handleTargets[key]++
|
||||
if handleTargets[key] > 1 {
|
||||
return nil, nil, nil, fmt.Errorf("节点 %s 的 %s 出口连接了多个目标", edge.Source, edge.SourceHandle)
|
||||
return nil, nil, nil, fmt.Errorf("node %s output %s is connected to multiple targets", edge.Source, edge.SourceHandle)
|
||||
}
|
||||
outgoing[edge.Source] = append(outgoing[edge.Source], edge)
|
||||
incoming[edge.Target]++
|
||||
@@ -145,7 +145,7 @@ func validateRequiredHandles(nodes []RuleNode, handleTargets map[string]int) err
|
||||
for _, node := range nodes {
|
||||
for _, handle := range requiredHandles(node.Type) {
|
||||
if handleTargets[node.ID+"\x00"+handle] == 0 {
|
||||
return fmt.Errorf("节点 %s 的 %s 出口未连接", node.ID, handle)
|
||||
return fmt.Errorf("node %s output %s is not connected", node.ID, handle)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,18 +156,18 @@ func validateRuleGraphConnectivity(nodes []RuleNode, startID string, outgoing ma
|
||||
reachable := walkRuleGraph(startID, outgoing)
|
||||
for _, node := range nodes {
|
||||
if !reachable[node.ID] {
|
||||
return fmt.Errorf("节点 %s 无法从开始节点到达", node.ID)
|
||||
return fmt.Errorf("node %s is not reachable from the start node", node.ID)
|
||||
}
|
||||
}
|
||||
for _, node := range nodes {
|
||||
if node.Type == RuleNodeStart && incoming[node.ID] != 0 {
|
||||
return fmt.Errorf("开始节点 %s 不能有入边", node.ID)
|
||||
return fmt.Errorf("start node %s must not have incoming edges", node.ID)
|
||||
}
|
||||
if node.Type != RuleNodeStart && incoming[node.ID] == 0 {
|
||||
return fmt.Errorf("节点 %s 必须至少有一条入边", node.ID)
|
||||
return fmt.Errorf("node %s must have at least one incoming edge", node.ID)
|
||||
}
|
||||
if (node.Type == RuleNodeAllow || node.Type == RuleNodeBlock) && len(outgoing[node.ID]) != 0 {
|
||||
return fmt.Errorf("终止节点 %s 不能有出口", node.ID)
|
||||
return fmt.Errorf("terminal node %s must not have outgoing edges", node.ID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -205,12 +205,12 @@ func validateIPMatchNodeConfig(ctx context.Context, node RuleNode, exists func(c
|
||||
}
|
||||
for _, raw := range cfg.IPs {
|
||||
if _, err := netip.ParseAddr(raw); err != nil {
|
||||
return fmt.Errorf("节点 %s 的 IP %s 无效", node.ID, raw)
|
||||
return fmt.Errorf("node %s contains invalid IP %s", node.ID, raw)
|
||||
}
|
||||
}
|
||||
for _, raw := range cfg.CIDRs {
|
||||
if _, err := netip.ParsePrefix(raw); err != nil {
|
||||
return fmt.Errorf("节点 %s 的 CIDR %s 无效", node.ID, raw)
|
||||
return fmt.Errorf("node %s contains invalid CIDR %s", node.ID, raw)
|
||||
}
|
||||
}
|
||||
for _, id := range cfg.IPGroupIDs {
|
||||
@@ -223,17 +223,17 @@ func validateIPMatchNodeConfig(ctx context.Context, node RuleNode, exists func(c
|
||||
|
||||
func validateIPGroupReference(ctx context.Context, nodeID string, id uint, exists func(context.Context, uint) (bool, error)) error {
|
||||
if id == 0 {
|
||||
return fmt.Errorf("节点 %s 引用的 IP 组 ID 无效", nodeID)
|
||||
return fmt.Errorf("node %s references an invalid IP group ID", nodeID)
|
||||
}
|
||||
if exists == nil {
|
||||
return fmt.Errorf("节点 %s 无法校验 IP 组 %d", nodeID, id)
|
||||
return fmt.Errorf("node %s cannot validate IP group %d", nodeID, id)
|
||||
}
|
||||
ok, err := exists(ctx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("节点 %s 校验 IP 组 %d 失败: %w", nodeID, id, err)
|
||||
return fmt.Errorf("node %s failed to validate IP group %d: %w", nodeID, id, err)
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Errorf("节点 %s 引用的 IP 组 %d 不存在", nodeID, id)
|
||||
return fmt.Errorf("node %s references missing IP group %d", nodeID, id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -245,12 +245,12 @@ func validateGeoMatchNodeConfig(node RuleNode) error {
|
||||
}
|
||||
for _, code := range cfg.Countries {
|
||||
if !countryCodePattern.MatchString(code) {
|
||||
return fmt.Errorf("节点 %s 的国家代码 %s 无效", node.ID, code)
|
||||
return fmt.Errorf("node %s contains invalid country code %s", node.ID, code)
|
||||
}
|
||||
}
|
||||
for _, code := range cfg.Regions {
|
||||
if !regionCodePattern.MatchString(code) {
|
||||
return fmt.Errorf("节点 %s 的地区代码 %s 无效", node.ID, code)
|
||||
return fmt.Errorf("node %s contains invalid region code %s", node.ID, code)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -262,16 +262,16 @@ func validatePoWNodeConfig(node RuleNode) error {
|
||||
return err
|
||||
}
|
||||
if cfg.Difficulty < 1 || cfg.Difficulty > 16 {
|
||||
return fmt.Errorf("节点 %s 的 PoW 难度必须在 1-16 之间", node.ID)
|
||||
return fmt.Errorf("PoW difficulty for node %s must be between 1 and 16", node.ID)
|
||||
}
|
||||
if cfg.Algorithm != powAlgorithmFast && cfg.Algorithm != powAlgorithmSlow {
|
||||
return fmt.Errorf("节点 %s 的 PoW 算法必须为 fast 或 slow", node.ID)
|
||||
return fmt.Errorf("PoW algorithm for node %s must be fast or slow", node.ID)
|
||||
}
|
||||
if cfg.SessionTTL < minPoWSessionTTLSeconds {
|
||||
return fmt.Errorf("节点 %s 的 PoW 会话 TTL 不能小于 60 秒", node.ID)
|
||||
return fmt.Errorf("PoW session TTL for node %s must be at least 60 seconds", node.ID)
|
||||
}
|
||||
if cfg.ChallengeTTL < minPoWChallengeTTLSeconds {
|
||||
return fmt.Errorf("节点 %s 的 PoW 挑战 TTL 不能小于 30 秒", node.ID)
|
||||
return fmt.Errorf("PoW challenge TTL for node %s must be at least 30 seconds", node.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -282,10 +282,10 @@ func validateBlockNodeConfig(node RuleNode) error {
|
||||
return err
|
||||
}
|
||||
if cfg.StatusCode < 400 || cfg.StatusCode > 599 {
|
||||
return fmt.Errorf("节点 %s 的阻止状态码必须在 400-599 之间", node.ID)
|
||||
return fmt.Errorf("block status code for node %s must be between 400 and 599", node.ID)
|
||||
}
|
||||
if len([]byte(cfg.ResponseBody)) > maxWAFBlockBodyBytes {
|
||||
return fmt.Errorf("节点 %s 的阻止响应体不能超过 %d 字节", node.ID, maxWAFBlockBodyBytes)
|
||||
return fmt.Errorf("block response body for node %s must not exceed %d bytes", node.ID, maxWAFBlockBodyBytes)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -300,34 +300,34 @@ func validateUACheckNodeConfig(node RuleNode) error {
|
||||
mode = UACheckMatchModeOr
|
||||
}
|
||||
if mode != UACheckMatchModeAnd && mode != UACheckMatchModeOr {
|
||||
return fmt.Errorf("节点 %s 的匹配模式必须为 and 或 or", node.ID)
|
||||
return fmt.Errorf("match mode for node %s must be and or or", node.ID)
|
||||
}
|
||||
for _, label := range cfg.Browsers {
|
||||
if !uaBrowserLabels[label] {
|
||||
return fmt.Errorf("节点 %s 的浏览器标签 %s 无效", node.ID, label)
|
||||
return fmt.Errorf("node %s contains invalid browser tag %s", node.ID, label)
|
||||
}
|
||||
}
|
||||
for _, label := range cfg.OperatingSystems {
|
||||
if !uaOSLabels[label] {
|
||||
return fmt.Errorf("节点 %s 的操作系统标签 %s 无效", node.ID, label)
|
||||
return fmt.Errorf("node %s contains invalid operating system tag %s", node.ID, label)
|
||||
}
|
||||
}
|
||||
if len(cfg.CustomUAPatterns) > maxUACustomPatterns {
|
||||
return fmt.Errorf("节点 %s 的自定义 UA 正则不能超过 %d 条", node.ID, maxUACustomPatterns)
|
||||
return fmt.Errorf("node %s must not contain more than %d custom User-Agent patterns", node.ID, maxUACustomPatterns)
|
||||
}
|
||||
for _, pattern := range cfg.CustomUAPatterns {
|
||||
if strings.TrimSpace(pattern) == "" {
|
||||
return fmt.Errorf("节点 %s 的自定义 UA 正则不能为空", node.ID)
|
||||
return fmt.Errorf("custom User-Agent pattern in node %s must not be empty", node.ID)
|
||||
}
|
||||
if len(pattern) > maxUACustomPatternBytes {
|
||||
return fmt.Errorf("节点 %s 的自定义 UA 正则不能超过 %d 字节", node.ID, maxUACustomPatternBytes)
|
||||
return fmt.Errorf("custom User-Agent pattern in node %s must not exceed %d bytes", node.ID, maxUACustomPatternBytes)
|
||||
}
|
||||
if _, err := regexp.Compile(pattern); err != nil {
|
||||
return fmt.Errorf("节点 %s 的自定义 UA 正则无效: %s", node.ID, pattern)
|
||||
return fmt.Errorf("invalid custom User-Agent pattern in node %s: %s", node.ID, pattern)
|
||||
}
|
||||
}
|
||||
if cfg.BlockCustomUA && len(cfg.CustomUAPatterns) == 0 {
|
||||
return fmt.Errorf("节点 %s 开启屏蔽自定义 UA 时至少需要一条正则", node.ID)
|
||||
return fmt.Errorf("node %s requires at least one pattern when custom User-Agent blocking is enabled", node.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -350,7 +350,7 @@ var uaOSLabels = map[string]bool{
|
||||
|
||||
func decodeNodeConfig(node RuleNode, dst any) error {
|
||||
if err := decodeStrictConfig(node.Config, dst); err != nil {
|
||||
return fmt.Errorf("节点 %s 的配置无效: %w", node.ID, err)
|
||||
return fmt.Errorf("invalid configuration for node %s: %w", node.ID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -358,7 +358,7 @@ func decodeNodeConfig(node RuleNode, dst any) error {
|
||||
func decodeStrictConfig(raw json.RawMessage, dst any) error {
|
||||
trimmed := bytes.TrimSpace(raw)
|
||||
if bytes.Equal(trimmed, []byte("null")) {
|
||||
return errors.New("配置不能为 null")
|
||||
return errors.New("configuration must not be null")
|
||||
}
|
||||
if len(trimmed) == 0 {
|
||||
raw = json.RawMessage(`{}`)
|
||||
@@ -369,7 +369,7 @@ func decodeStrictConfig(raw json.RawMessage, dst any) error {
|
||||
return err
|
||||
}
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
return errors.New("配置包含额外 JSON 值")
|
||||
return errors.New("configuration contains an additional JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -451,7 +451,7 @@ func validateTerminalPaths(nodes []RuleNode, outgoing map[string][]RuleEdge) err
|
||||
}
|
||||
for _, node := range nodes {
|
||||
if !terminating[node.ID] {
|
||||
return fmt.Errorf("节点 %s 不存在通往终止节点的路径", node.ID)
|
||||
return fmt.Errorf("node %s has no path to a terminal node", node.ID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -43,71 +43,71 @@ func TestValidateRuleGraph(t *testing.T) {
|
||||
}{
|
||||
{"duplicate start", func(g *RuleGraph) {
|
||||
g.Nodes = append(g.Nodes, RuleNode{ID: "start-2", Type: RuleNodeStart, Config: rawConfig(`{}`)})
|
||||
}, "恰好包含一个开始节点"},
|
||||
}, "rule graph must contain exactly one start node"},
|
||||
{"duplicate allow", func(g *RuleGraph) {
|
||||
g.Nodes = append(g.Nodes, RuleNode{ID: "allow-2", Type: RuleNodeAllow, Config: rawConfig(`{}`)})
|
||||
}, "恰好包含一个通过节点"},
|
||||
}, "rule graph must contain exactly one allow node"},
|
||||
{"cycle", func(g *RuleGraph) {
|
||||
g.Edges[2].Target = "start"
|
||||
}, "规则图不能包含循环"},
|
||||
}, "rule graph must not contain cycles"},
|
||||
{"unreachable", func(g *RuleGraph) {
|
||||
g.Nodes = append(g.Nodes, RuleNode{ID: "orphan", Type: RuleNodeBlock, Config: rawConfig(`{"status_code":403,"response_body":""}`)})
|
||||
}, "节点 orphan 无法从开始节点到达"},
|
||||
{"missing false edge", func(g *RuleGraph) { g.Edges = g.Edges[:2] }, "节点 match-1 的 false 出口未连接"},
|
||||
{"wrong handle", func(g *RuleGraph) { g.Edges[0].SourceHandle = "true" }, "边 e1 的源端口 true 不适用于节点 start"},
|
||||
}, "node orphan is not reachable from the start node"},
|
||||
{"missing false edge", func(g *RuleGraph) { g.Edges = g.Edges[:2] }, "node match-1 output false is not connected"},
|
||||
{"wrong handle", func(g *RuleGraph) { g.Edges[0].SourceHandle = "true" }, "edge e1 source port true is not valid for node start"},
|
||||
{"same handle multiple targets", func(g *RuleGraph) {
|
||||
g.Edges = append(g.Edges, RuleEdge{ID: "e4", Source: "match-1", SourceHandle: "true", Target: "allow"})
|
||||
}, "节点 match-1 的 true 出口连接了多个目标"},
|
||||
{"unknown type", func(g *RuleGraph) { g.Nodes[1].Type = RuleNodeType("script") }, "节点 match-1 的类型 script 未知"},
|
||||
{"dangling target", func(g *RuleGraph) { g.Edges[1].Target = "missing" }, "边 e2 的目标节点 missing 不存在"},
|
||||
{"invalid ip", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`{"ips":["bad"]}`) }, "节点 match-1 的 IP bad 无效"},
|
||||
{"invalid cidr", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`{"cidrs":["bad"]}`) }, "节点 match-1 的 CIDR bad 无效"},
|
||||
{"missing ip group", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`{"ip_group_ids":[99]}`) }, "节点 match-1 引用的 IP 组 99 不存在"},
|
||||
}, "node match-1 output true is connected to multiple targets"},
|
||||
{"unknown type", func(g *RuleGraph) { g.Nodes[1].Type = RuleNodeType("script") }, "node match-1 has unknown type script"},
|
||||
{"dangling target", func(g *RuleGraph) { g.Edges[1].Target = "missing" }, "edge e2 references missing target node missing"},
|
||||
{"invalid ip", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`{"ips":["bad"]}`) }, "node match-1 contains invalid IP bad"},
|
||||
{"invalid cidr", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`{"cidrs":["bad"]}`) }, "node match-1 contains invalid CIDR bad"},
|
||||
{"missing ip group", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`{"ip_group_ids":[99]}`) }, "node match-1 references missing IP group 99"},
|
||||
{"invalid country", func(g *RuleGraph) {
|
||||
g.Nodes[1].Type = RuleNodeGeoMatch
|
||||
g.Nodes[1].Config = rawConfig(`{"countries":["USA"]}`)
|
||||
}, "节点 match-1 的国家代码 USA 无效"},
|
||||
}, "node match-1 contains invalid country code USA"},
|
||||
{"invalid region", func(g *RuleGraph) {
|
||||
g.Nodes[1].Type = RuleNodeGeoMatch
|
||||
g.Nodes[1].Config = rawConfig(`{"regions":["US-"]}`)
|
||||
}, "节点 match-1 的地区代码 US- 无效"},
|
||||
}, "node match-1 contains invalid region code US-"},
|
||||
{"pow range", func(g *RuleGraph) {
|
||||
g.Nodes[1].Type = RuleNodePoW
|
||||
g.Nodes[1].Config = rawConfig(`{"algorithm":"fast","difficulty":17,"session_ttl":60,"challenge_ttl":30}`)
|
||||
g.Edges[1].SourceHandle = "next"
|
||||
g.Edges = g.Edges[:2]
|
||||
}, "节点 match-1 的 PoW 难度必须在 1-16 之间"},
|
||||
}, "PoW difficulty for node match-1 must be between 1 and 16"},
|
||||
{"invalid ua browser", func(g *RuleGraph) {
|
||||
g.Nodes[1].Type = RuleNodeUACheck
|
||||
g.Nodes[1].Config = rawConfig(`{"browsers":["NotABrowser"],"match_mode":"or"}`)
|
||||
}, "节点 match-1 的浏览器标签 NotABrowser 无效"},
|
||||
}, "node match-1 contains invalid browser tag NotABrowser"},
|
||||
{"invalid ua match mode", func(g *RuleGraph) {
|
||||
g.Nodes[1].Type = RuleNodeUACheck
|
||||
g.Nodes[1].Config = rawConfig(`{"match_mode":"xor"}`)
|
||||
}, "节点 match-1 的匹配模式必须为 and 或 or"},
|
||||
}, "match mode for node match-1 must be and or or"},
|
||||
{"invalid ua custom regex", func(g *RuleGraph) {
|
||||
g.Nodes[1].Type = RuleNodeUACheck
|
||||
g.Nodes[1].Config = rawConfig(`{"block_custom_ua":true,"custom_ua_patterns":["("]}`)
|
||||
}, "节点 match-1 的自定义 UA 正则无效"},
|
||||
}, "invalid custom User-Agent pattern in node match-1"},
|
||||
{"custom ua requires patterns", func(g *RuleGraph) {
|
||||
g.Nodes[1].Type = RuleNodeUACheck
|
||||
g.Nodes[1].Config = rawConfig(`{"block_custom_ua":true}`)
|
||||
}, "节点 match-1 开启屏蔽自定义 UA 时至少需要一条正则"},
|
||||
{"unknown config field", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`{"ips":[],"surprise":true}`) }, "节点 match-1 的配置无效"},
|
||||
{"null config", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`null`) }, "节点 match-1 的配置无效"},
|
||||
}, "node match-1 requires at least one pattern when custom User-Agent blocking is enabled"},
|
||||
{"unknown config field", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`{"ips":[],"surprise":true}`) }, "invalid configuration for node match-1"},
|
||||
{"null config", func(g *RuleGraph) { g.Nodes[1].Config = rawConfig(`null`) }, "invalid configuration for node match-1"},
|
||||
{"too many nodes", func(g *RuleGraph) {
|
||||
for i := 0; i < 125; i++ {
|
||||
g.Nodes = append(g.Nodes, RuleNode{ID: strings.Repeat("x", i+1), Type: RuleNodeBlock, Config: rawConfig(`{"status_code":403}`)})
|
||||
}
|
||||
}, "规则图节点数不能超过 128"},
|
||||
}, "rule graph must not contain more than 128 nodes"},
|
||||
{"too many edges", func(g *RuleGraph) {
|
||||
for i := 0; i < 254; i++ {
|
||||
g.Edges = append(g.Edges, RuleEdge{ID: strings.Repeat("e", i+5), Source: "start", SourceHandle: "next", Target: "allow"})
|
||||
}
|
||||
}, "规则图边数不能超过 256"},
|
||||
}, "rule graph must not contain more than 256 edges"},
|
||||
{"graph too large", func(g *RuleGraph) {
|
||||
g.Nodes[0].Label = strings.Repeat("x", 256*1024)
|
||||
}, "规则图大小不能超过 256 KiB"},
|
||||
}, "rule graph must not exceed 256 KiB"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -127,7 +127,7 @@ func TestValidateRuleGraphDetectsNodeWithoutTerminalPath(t *testing.T) {
|
||||
nodes := []RuleNode{{ID: "start", Type: RuleNodeStart}, {ID: "match", Type: RuleNodeIPMatch}, {ID: "allow", Type: RuleNodeAllow}}
|
||||
outgoing := map[string][]RuleEdge{"start": {{Source: "start", Target: "match"}}}
|
||||
err := validateTerminalPaths(nodes, outgoing)
|
||||
if err == nil || !strings.Contains(err.Error(), "节点 start 不存在通往终止节点的路径") {
|
||||
if err == nil || !strings.Contains(err.Error(), "node start has no path to a terminal node") {
|
||||
t.Fatalf("validateTerminalPaths() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ func SyncDueWAFIPGroups(ctx context.Context) error {
|
||||
|
||||
func syncOpenFlareWAFIPGroup(ctx context.Context, group *model.OpenFlareWAFIPGroup, now time.Time) (*IPGroupSyncResult, error) {
|
||||
if group == nil {
|
||||
return nil, errors.New("IP 组不存在")
|
||||
return nil, errors.New("IP group was not found")
|
||||
}
|
||||
switch group.Type {
|
||||
case wafIPGroupTypeSubscription:
|
||||
@@ -158,7 +158,7 @@ func syncOpenFlareWAFIPGroup(ctx context.Context, group *model.OpenFlareWAFIPGro
|
||||
case wafIPGroupTypeAutomatic:
|
||||
return syncIPGroupAutomatic(ctx, group, now)
|
||||
default:
|
||||
return nil, &RuleValidationError{Err: errors.New("只有自动和订阅类型 IP 组支持同步")}
|
||||
return nil, &RuleValidationError{Err: errors.New("only automatic and subscription IP groups support synchronization")}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ func syncIPGroupSubscription(ctx context.Context, group *model.OpenFlareWAFIPGro
|
||||
group.LastSyncedAt = &now
|
||||
group.NextSyncAt = &nextSyncAt
|
||||
group.LastSyncStatus = "success"
|
||||
group.LastSyncMessage = fmt.Sprintf("同步成功,共 %d 条 IP/IP 段", len(ips))
|
||||
group.LastSyncMessage = fmt.Sprintf("Synchronization completed; %d IP addresses or ranges", len(ips))
|
||||
if err := repository.UpdateOpenFlareWAFIPGroupSyncResult(ctx, group); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -265,7 +265,7 @@ func syncIPGroupAutomatic(ctx context.Context, group *model.OpenFlareWAFIPGroup,
|
||||
group.LastSyncedAt = &now
|
||||
group.NextSyncAt = &nextSyncAt
|
||||
group.LastSyncStatus = "success"
|
||||
group.LastSyncMessage = fmt.Sprintf("自动规则执行成功,共命中 %d 个 IP,当前生效 %d 个 IP", len(ips), len(finalIPs))
|
||||
group.LastSyncMessage = fmt.Sprintf("Automatic rules completed; matched %d IPs, currently active %d IPs", len(ips), len(finalIPs))
|
||||
if err := repository.UpdateOpenFlareWAFIPGroupSyncResult(ctx, group); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -301,7 +301,7 @@ func evaluateParsedIPGroupAutoConfig(ctx context.Context, config ipGroupAutoConf
|
||||
for i, rule := range config.Rules {
|
||||
program, err := exprlang.Compile(rule.Expr, exprlang.Env(ipGroupAutoRuleEnv{}), exprlang.AsBool())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("自动规则 %s Expr 无效: %w", displayIPGroupAutoRuleName(rule, i), err)
|
||||
return nil, fmt.Errorf("invalid expression in automatic rule %s: %w", displayIPGroupAutoRuleName(rule, i), err)
|
||||
}
|
||||
programs = append(programs, program)
|
||||
}
|
||||
@@ -348,7 +348,7 @@ func evaluateParsedIPGroupAutoConfig(ctx context.Context, config ipGroupAutoConf
|
||||
for _, program := range programs {
|
||||
output, err := exprlang.Run(program, env)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("执行自动规则失败: %w", err)
|
||||
return nil, fmt.Errorf("failed to execute automatic rule: %w", err)
|
||||
}
|
||||
if matchedRule, ok := output.(bool); ok && matchedRule {
|
||||
matched = append(matched, acc.ip)
|
||||
@@ -409,23 +409,23 @@ func downloadIPGroupSubscription(ctx context.Context, rawURL string) ([]byte, er
|
||||
client := http.Client{Timeout: 15 * time.Second}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("下载订阅失败: %w", err)
|
||||
return nil, fmt.Errorf("failed to download subscription: %w", err)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("下载订阅失败: %w", err)
|
||||
return nil, fmt.Errorf("failed to download subscription: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("订阅返回状态码 %d", resp.StatusCode)
|
||||
return nil, fmt.Errorf("subscription returned status code %d", resp.StatusCode)
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
reader := io.LimitReader(resp.Body, maxWAFIPGroupSubscriptionBytes+1)
|
||||
if _, err := buffer.ReadFrom(reader); err != nil {
|
||||
return nil, fmt.Errorf("读取订阅内容失败: %w", err)
|
||||
return nil, fmt.Errorf("failed to read subscription content: %w", err)
|
||||
}
|
||||
if buffer.Len() > maxWAFIPGroupSubscriptionBytes {
|
||||
return nil, fmt.Errorf("订阅内容不能超过 %d 字节", maxWAFIPGroupSubscriptionBytes)
|
||||
return nil, fmt.Errorf("subscription content must not exceed %d bytes", maxWAFIPGroupSubscriptionBytes)
|
||||
}
|
||||
return buffer.Bytes(), nil
|
||||
}
|
||||
@@ -459,7 +459,7 @@ func parseIPGroupTextSubscription(text string) []string {
|
||||
func parseIPGroupJSONSubscription(content []byte, mappingRule string) ([]string, error) {
|
||||
var payload any
|
||||
if err := json.Unmarshal(content, &payload); err != nil {
|
||||
return nil, fmt.Errorf("JSON 订阅解析失败: %w", err)
|
||||
return nil, fmt.Errorf("failed to parse JSON subscription: %w", err)
|
||||
}
|
||||
nodes, err := selectJSONMappingNodes(payload, mappingRule)
|
||||
if err != nil {
|
||||
@@ -470,7 +470,7 @@ func parseIPGroupJSONSubscription(content []byte, mappingRule string) ([]string,
|
||||
collectJSONStrings(node, &items)
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return nil, errors.New("JSON 订阅没有解析到 IP/IP 段")
|
||||
return nil, errors.New("no IP addresses or ranges were parsed from the JSON subscription")
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -512,7 +512,7 @@ func selectJSONMappingNodes(payload any, mappingRule string) ([]any, error) {
|
||||
nodes = next
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, fmt.Errorf("JSON 映射规则 %q 未匹配到内容", mappingRule)
|
||||
return nil, fmt.Errorf("JSON mapping rule %q did not match any content", mappingRule)
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ func EnsureDefaultRuleGroup(ctx context.Context) error {
|
||||
return marshalErr
|
||||
}
|
||||
group := &model.OpenFlareWAFRuleGroup{
|
||||
Name: "全局规则组", Enabled: true, IsGlobal: true, Graph: string(graph), Revision: 1,
|
||||
Name: "Global rule group", Enabled: true, IsGlobal: true, Graph: string(graph), Revision: 1,
|
||||
}
|
||||
return repository.CreateOpenFlareWAFRuleGroup(ctx, group)
|
||||
}
|
||||
@@ -308,7 +308,7 @@ func DeleteIPGroup(ctx context.Context, id uint) error {
|
||||
return err
|
||||
}
|
||||
if counts[group.ID] > 0 {
|
||||
return &RuleValidationError{Err: errors.New("IP 组已被 WAF 规则引用,请先移除引用")}
|
||||
return &RuleValidationError{Err: errors.New("IP group is referenced by WAF rules; remove the references first")}
|
||||
}
|
||||
return repository.DeleteOpenFlareWAFIPGroup(ctx, group.ID)
|
||||
}
|
||||
@@ -412,13 +412,13 @@ func normalizeIPList(items []string) ([]string, error) {
|
||||
if strings.Contains(item, "/") {
|
||||
prefix, err := netip.ParsePrefix(item)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s 不是合法 IP 段", item)
|
||||
return nil, fmt.Errorf("%s is not a valid IP range", item)
|
||||
}
|
||||
item = prefix.Masked().String()
|
||||
} else {
|
||||
addr, err := netip.ParseAddr(item)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s 不是合法 IP", item)
|
||||
return nil, fmt.Errorf("%s is not a valid IP address", item)
|
||||
}
|
||||
item = addr.String()
|
||||
}
|
||||
@@ -446,10 +446,10 @@ func normalizeRuleGroupIDs(ctx context.Context, groupIDs []uint) ([]uint, error)
|
||||
for _, groupID := range normalized {
|
||||
group, err := repository.GetOpenFlareWAFRuleGroupByID(ctx, groupID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("WAF 规则组 %d 不存在", groupID)
|
||||
return nil, fmt.Errorf("WAF rule group %d was not found", groupID)
|
||||
}
|
||||
if group.IsGlobal {
|
||||
return nil, errors.New("全局 WAF 规则组不需要手动绑定")
|
||||
return nil, errors.New("global WAF rule groups do not require manual binding")
|
||||
}
|
||||
}
|
||||
return normalized, nil
|
||||
@@ -504,11 +504,11 @@ func parseIPGroupAutoConfig(raw json.RawMessage) (ipGroupAutoConfig, error) {
|
||||
}
|
||||
var object map[string]any
|
||||
if err := json.Unmarshal([]byte(text), &object); err != nil || object == nil {
|
||||
return ipGroupAutoConfig{}, errors.New("自动 IP 组配置必须是 JSON 对象")
|
||||
return ipGroupAutoConfig{}, errors.New("automatic IP group configuration must be a JSON object")
|
||||
}
|
||||
var config ipGroupAutoConfig
|
||||
if err := json.Unmarshal([]byte(text), &config); err != nil {
|
||||
return ipGroupAutoConfig{}, errors.New("自动 IP 组配置必须是 JSON 对象")
|
||||
return ipGroupAutoConfig{}, errors.New("automatic IP group configuration must be a JSON object")
|
||||
}
|
||||
lookbackDur, lookbackText, err := resolveIPGroupAutoLookback(object)
|
||||
if err != nil {
|
||||
@@ -526,10 +526,10 @@ func parseIPGroupAutoConfig(raw json.RawMessage) (ipGroupAutoConfig, error) {
|
||||
rule.Name = strings.TrimSpace(rule.Name)
|
||||
rule.Expr = strings.TrimSpace(rule.Expr)
|
||||
if rule.Expr == "" {
|
||||
return ipGroupAutoConfig{}, fmt.Errorf("自动规则 %d 的 Expr 表达式不能为空", i+1)
|
||||
return ipGroupAutoConfig{}, fmt.Errorf("expression in automatic rule %d must not be empty", i+1)
|
||||
}
|
||||
if _, err := exprlang.Compile(rule.Expr, exprlang.Env(ipGroupAutoRuleEnv{}), exprlang.AsBool()); err != nil {
|
||||
return ipGroupAutoConfig{}, fmt.Errorf("自动规则 %s Expr 无效: %w", displayIPGroupAutoRuleName(rule, i), err)
|
||||
return ipGroupAutoConfig{}, fmt.Errorf("invalid expression in automatic rule %s: %w", displayIPGroupAutoRuleName(rule, i), err)
|
||||
}
|
||||
config.Rules[i] = rule
|
||||
}
|
||||
@@ -549,14 +549,14 @@ func resolveIPGroupAutoLookback(object map[string]any) (time.Duration, string, e
|
||||
// legacy: minutes as number or numeric string
|
||||
minutes, err := parsePositiveNumber(raw)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("lookback_minutes 无效: %w", err)
|
||||
return 0, "", fmt.Errorf("invalid lookback_minutes: %w", err)
|
||||
}
|
||||
if minutes <= 0 {
|
||||
return defaultWAFIPGroupAutoLookbackDur, defaultWAFIPGroupAutoLookback, nil
|
||||
}
|
||||
dur := time.Duration(minutes) * time.Minute
|
||||
if dur > maxWAFIPGroupAutoLookback {
|
||||
return 0, "", fmt.Errorf("回看窗口不能超过 %s", formatLookbackDuration(maxWAFIPGroupAutoLookback))
|
||||
return 0, "", fmt.Errorf("lookback window must not exceed %s", formatLookbackDuration(maxWAFIPGroupAutoLookback))
|
||||
}
|
||||
return dur, formatLookbackDuration(dur), nil
|
||||
}
|
||||
@@ -574,20 +574,20 @@ func parseIPGroupLookbackValue(raw any) (time.Duration, string, error) {
|
||||
if isAllDigits(trimmed) {
|
||||
minutes, err := parsePositiveNumber(trimmed)
|
||||
if err != nil || minutes <= 0 {
|
||||
return 0, "", errors.New("lookback 格式不合法,请使用 60m、1h 等时长")
|
||||
return 0, "", errors.New("invalid lookback format; use a duration such as 60m or 1h")
|
||||
}
|
||||
dur := time.Duration(minutes) * time.Minute
|
||||
if dur > maxWAFIPGroupAutoLookback {
|
||||
return 0, "", fmt.Errorf("回看窗口不能超过 %s", formatLookbackDuration(maxWAFIPGroupAutoLookback))
|
||||
return 0, "", fmt.Errorf("lookback window must not exceed %s", formatLookbackDuration(maxWAFIPGroupAutoLookback))
|
||||
}
|
||||
return dur, formatLookbackDuration(dur), nil
|
||||
}
|
||||
dur, err := time.ParseDuration(strings.ToLower(trimmed))
|
||||
if err != nil || dur <= 0 {
|
||||
return 0, "", errors.New("lookback 格式不合法,请使用 60m、1h 等时长")
|
||||
return 0, "", errors.New("invalid lookback format; use a duration such as 60m or 1h")
|
||||
}
|
||||
if dur > maxWAFIPGroupAutoLookback {
|
||||
return 0, "", fmt.Errorf("回看窗口不能超过 %s", formatLookbackDuration(maxWAFIPGroupAutoLookback))
|
||||
return 0, "", fmt.Errorf("lookback window must not exceed %s", formatLookbackDuration(maxWAFIPGroupAutoLookback))
|
||||
}
|
||||
return dur, formatLookbackDuration(dur), nil
|
||||
case float64:
|
||||
@@ -595,17 +595,17 @@ func parseIPGroupLookbackValue(raw any) (time.Duration, string, error) {
|
||||
return defaultWAFIPGroupAutoLookbackDur, defaultWAFIPGroupAutoLookback, nil
|
||||
}
|
||||
if v != float64(int64(v)) {
|
||||
return 0, "", errors.New("lookback 数值必须为整数分钟")
|
||||
return 0, "", errors.New("lookback must be a whole number of minutes")
|
||||
}
|
||||
dur := time.Duration(int64(v)) * time.Minute
|
||||
if dur > maxWAFIPGroupAutoLookback {
|
||||
return 0, "", fmt.Errorf("回看窗口不能超过 %s", formatLookbackDuration(maxWAFIPGroupAutoLookback))
|
||||
return 0, "", fmt.Errorf("lookback window must not exceed %s", formatLookbackDuration(maxWAFIPGroupAutoLookback))
|
||||
}
|
||||
return dur, formatLookbackDuration(dur), nil
|
||||
case json.Number:
|
||||
return parseIPGroupLookbackValue(string(v))
|
||||
default:
|
||||
return 0, "", errors.New("lookback 格式不合法,请使用 60m、1h 等时长")
|
||||
return 0, "", errors.New("invalid lookback format; use a duration such as 60m or 1h")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -613,7 +613,7 @@ func parsePositiveNumber(raw any) (int, error) {
|
||||
switch v := raw.(type) {
|
||||
case float64:
|
||||
if v != float64(int(v)) {
|
||||
return 0, errors.New("必须为整数")
|
||||
return 0, errors.New("must be an integer")
|
||||
}
|
||||
return int(v), nil
|
||||
case int:
|
||||
@@ -629,7 +629,7 @@ func parsePositiveNumber(raw any) (int, error) {
|
||||
case string:
|
||||
trimmed := strings.TrimSpace(v)
|
||||
if trimmed == "" || !isAllDigits(trimmed) {
|
||||
return 0, errors.New("必须为整数")
|
||||
return 0, errors.New("must be an integer")
|
||||
}
|
||||
n := 0
|
||||
for _, ch := range trimmed {
|
||||
@@ -637,7 +637,7 @@ func parsePositiveNumber(raw any) (int, error) {
|
||||
}
|
||||
return n, nil
|
||||
default:
|
||||
return 0, errors.New("必须为整数")
|
||||
return 0, errors.New("must be an integer")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -673,10 +673,10 @@ func formatLookbackDuration(d time.Duration) string {
|
||||
func validateSubscriptionURL(rawURL string) error {
|
||||
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil || parsed.Host == "" {
|
||||
return errors.New("订阅 URL 无效")
|
||||
return errors.New("invalid subscription URL")
|
||||
}
|
||||
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return errors.New("订阅 URL 仅支持 http 或 https")
|
||||
return errors.New("subscription URL must use HTTP or HTTPS")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -729,11 +729,11 @@ func nextIPGroupSyncAt(groupType string, enabled bool, interval int, current *ti
|
||||
func buildIPGroup(group *model.OpenFlareWAFIPGroup, input IPGroupInput) (*model.OpenFlareWAFIPGroup, error) {
|
||||
name := strings.TrimSpace(input.Name)
|
||||
if name == "" {
|
||||
return nil, errors.New("IP 组名称不能为空")
|
||||
return nil, errors.New("IP group name must not be empty")
|
||||
}
|
||||
groupType := normalizeIPGroupType(input.Type)
|
||||
if groupType == "" {
|
||||
return nil, errors.New("IP 组类型无效")
|
||||
return nil, errors.New("invalid IP group type")
|
||||
}
|
||||
ipList := input.IPList
|
||||
subscriptionURL := ""
|
||||
|
||||
@@ -96,7 +96,7 @@ func GetRule(ctx context.Context, id uint) (*RuleView, error) {
|
||||
func CreateRule(ctx context.Context, input CreateRuleInput) (*RuleView, error) {
|
||||
name := strings.TrimSpace(input.Name)
|
||||
if name == "" {
|
||||
return nil, &RuleValidationError{Err: errors.New("WAF 规则名称不能为空")}
|
||||
return nil, &RuleValidationError{Err: errors.New("WAF rule name must not be empty")}
|
||||
}
|
||||
raw, err := json.Marshal(DefaultRuleGraph())
|
||||
if err != nil {
|
||||
@@ -123,7 +123,7 @@ func UpdateRuleMeta(ctx context.Context, id uint, input UpdateRuleMetaInput) (*R
|
||||
}
|
||||
name := strings.TrimSpace(input.Name)
|
||||
if name == "" {
|
||||
return nil, &RuleValidationError{Err: errors.New("WAF 规则名称不能为空")}
|
||||
return nil, &RuleValidationError{Err: errors.New("WAF rule name must not be empty")}
|
||||
}
|
||||
group.Name, group.Enabled = name, input.Enabled
|
||||
if err = repository.UpdateOpenFlareWAFRuleGroup(ctx, group); err != nil {
|
||||
@@ -139,7 +139,7 @@ func DeleteRuleGroup(ctx context.Context, id uint) error {
|
||||
return err
|
||||
}
|
||||
if group.IsGlobal {
|
||||
return &RuleValidationError{Err: errors.New("全局 WAF 规则不能删除")}
|
||||
return &RuleValidationError{Err: errors.New("global WAF rule cannot be deleted")}
|
||||
}
|
||||
return repository.DeleteOpenFlareWAFRuleGroupWithBindings(ctx, id)
|
||||
}
|
||||
@@ -150,7 +150,7 @@ func SaveRuleGraph(ctx context.Context, id uint, input SaveRuleGraphInput) (*Rul
|
||||
return nil, err
|
||||
}
|
||||
if err := ValidateRuleGraph(ctx, input.Graph, ruleIPGroupExists); err != nil {
|
||||
return nil, &RuleValidationError{Err: fmt.Errorf("规则图无效: %w", err)}
|
||||
return nil, &RuleValidationError{Err: fmt.Errorf("invalid rule graph: %w", err)}
|
||||
}
|
||||
raw, err := json.Marshal(input.Graph)
|
||||
if err != nil {
|
||||
|
||||
@@ -46,7 +46,7 @@ func TestDeleteIPGroupRejectsGraphReference(t *testing.T) {
|
||||
view, err := GetIPGroup(ctx, group.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, view.ReferencedByRuleCount)
|
||||
require.ErrorContains(t, DeleteIPGroup(ctx, group.ID), "已被 WAF 规则引用")
|
||||
require.ErrorContains(t, DeleteIPGroup(ctx, group.ID), "referenced by WAF rules")
|
||||
}
|
||||
|
||||
func TestRuleHandlersMapFailures(t *testing.T) {
|
||||
@@ -129,7 +129,7 @@ func TestCreateRuleRejectsEmptyName(t *testing.T) {
|
||||
defer cleanup()
|
||||
|
||||
_, err := CreateRule(context.Background(), CreateRuleInput{Name: " "})
|
||||
require.ErrorContains(t, err, "名称不能为空")
|
||||
require.ErrorContains(t, err, "name must not be empty")
|
||||
}
|
||||
|
||||
func TestSaveRuleGraphValidationAndRevisionConflict(t *testing.T) {
|
||||
|
||||
@@ -24,12 +24,12 @@ func handleRuleError(c *gin.Context, err error) bool {
|
||||
case errors.As(err, &validation):
|
||||
response.AbortBadRequest(c, validation.Error())
|
||||
case errors.Is(err, model.ErrWAFRuleRevisionConflict):
|
||||
response.AbortConflict(c, "规则已被其他操作更新,请重新加载")
|
||||
response.AbortConflict(c, "Rule was updated by another operation; reload it")
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
response.AbortNotFound(c, "WAF 规则不存在")
|
||||
response.AbortNotFound(c, "WAF rule was not found")
|
||||
default:
|
||||
logger.ErrorF(c.Request.Context(), "[OpenFlareWAF] rule API failed: %v", err)
|
||||
response.AbortInternal(c, "WAF 规则操作失败")
|
||||
response.AbortInternal(c, "WAF rule operation failed")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user