Skip to content

Commit

Permalink
feat: add subnet validation (#1275)
Browse files Browse the repository at this point in the history
  • Loading branch information
songquanpeng committed Apr 5, 2024
1 parent c49778c commit 6860580
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
8 changes: 7 additions & 1 deletion common/network/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ package network

import (
"context"
"fmt"
"github.com/songquanpeng/one-api/common/logger"
"net"
)

func IsValidSubnet(subnet string) error {
_, _, err := net.ParseCIDR(subnet)
return fmt.Errorf("failed to parse subnet: %w", err)
}

func IsIpInSubnet(ctx context.Context, ip string, subnet string) bool {
_, ipNet, err := net.ParseCIDR(subnet)
if err != nil {
logger.Errorf(ctx, "failed to parse subnet: %s, subnet: %s", err.Error(), subnet)
logger.Errorf(ctx, "failed to parse subnet: %s", err.Error())
return false
}
return ipNet.Contains(net.ParseIP(ip))
Expand Down
26 changes: 22 additions & 4 deletions controller/token.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package controller

import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/songquanpeng/one-api/common"
"github.com/songquanpeng/one-api/common/config"
"github.com/songquanpeng/one-api/common/helper"
"github.com/songquanpeng/one-api/common/network"
"github.com/songquanpeng/one-api/model"
"net/http"
"strconv"
Expand Down Expand Up @@ -104,6 +106,19 @@ func GetTokenStatus(c *gin.Context) {
})
}

func validateToken(c *gin.Context, token model.Token) error {
if len(token.Name) > 30 {
return fmt.Errorf("令牌名称过长")
}
if token.Subnet != nil && *token.Subnet != "" {
err := network.IsValidSubnet(*token.Subnet)
if err != nil {
return fmt.Errorf("无效的网段:%s", err.Error())
}
}
return nil
}

func AddToken(c *gin.Context) {
token := model.Token{}
err := c.ShouldBindJSON(&token)
Expand All @@ -114,13 +129,15 @@ func AddToken(c *gin.Context) {
})
return
}
if len(token.Name) > 30 {
err = validateToken(c, token)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "令牌名称过长",
"message": fmt.Sprintf("参数错误:%s", err.Error()),
})
return
}

cleanToken := model.Token{
UserId: c.GetInt("id"),
Name: token.Name,
Expand Down Expand Up @@ -179,10 +196,11 @@ func UpdateToken(c *gin.Context) {
})
return
}
if len(token.Name) > 30 {
err = validateToken(c, token)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "令牌名称过长",
"message": fmt.Sprintf("参数错误:%s", err.Error()),
})
return
}
Expand Down

0 comments on commit 6860580

Please sign in to comment.