Initial commit (code only without large binaries)

This commit is contained in:
robin
2026-02-15 18:58:44 +08:00
commit 35df75498f
9442 changed files with 1495866 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type DeleteTaskAction struct {
actionutils.ParentAction
}
func (this *DeleteTaskAction) RunPost(params struct {
TaskId int64
}) {
defer this.CreateLogInfo(codes.HTTPCacheTask_LogDeleteHTTPCacheTask, params.TaskId)
_, err := this.RPC().HTTPCacheTaskRPC().DeleteHTTPCacheTask(this.AdminContext(), &pb.DeleteHTTPCacheTaskRequest{
HttpCacheTaskId: params.TaskId,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,98 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/cache/cacheutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"strings"
)
type FetchAction struct {
actionutils.ParentAction
}
func (this *FetchAction) Init() {
this.Nav("", "", "fetch")
}
func (this *FetchAction) RunGet(params struct{}) {
// 初始化菜单数据
err := InitMenu(this.Parent())
if err != nil {
this.ErrorPage(err)
return
}
this.Show()
}
func (this *FetchAction) RunPost(params struct {
Keys string
Must *actions.Must
CSRF *actionutils.CSRF
}) {
defer this.CreateLogInfo(codes.HTTPCacheTask_LogCreateHTTPCacheTaskFetch)
if len(params.Keys) == 0 {
this.Fail("请输入要预热的Key列表")
}
// 检查Key
var realKeys = []string{}
for _, key := range strings.Split(params.Keys, "\n") {
key = strings.TrimSpace(key)
if len(key) == 0 {
continue
}
if lists.ContainsString(realKeys, key) {
continue
}
realKeys = append(realKeys, key)
}
if len(realKeys) == 0 {
this.Fail("请输入要预热的Key列表")
}
// 校验Key
validateResp, err := this.RPC().HTTPCacheTaskKeyRPC().ValidateHTTPCacheTaskKeys(this.AdminContext(), &pb.ValidateHTTPCacheTaskKeysRequest{Keys: realKeys})
if err != nil {
this.ErrorPage(err)
return
}
var failKeyMaps = []maps.Map{}
if len(validateResp.FailKeys) > 0 {
for _, key := range validateResp.FailKeys {
failKeyMaps = append(failKeyMaps, maps.Map{
"key": key.Key,
"reason": cacheutils.KeyFailReason(key.ReasonCode),
})
}
}
this.Data["failKeys"] = failKeyMaps
if len(failKeyMaps) > 0 {
this.Fail("有" + types.String(len(failKeyMaps)) + "个Key无法完成操作请删除后重试")
}
// 提交任务
_, err = this.RPC().HTTPCacheTaskRPC().CreateHTTPCacheTask(this.AdminContext(), &pb.CreateHTTPCacheTaskRequest{
Type: "fetch",
KeyType: "key",
Keys: realKeys,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,103 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/cache/cacheutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"strings"
)
type IndexAction struct {
actionutils.ParentAction
}
func (this *IndexAction) Init() {
this.Nav("", "", "purge")
}
func (this *IndexAction) RunGet(params struct {
KeyType string
}) {
// 初始化菜单数据
err := InitMenu(this.Parent())
if err != nil {
this.ErrorPage(err)
return
}
this.Data["keyType"] = params.KeyType
this.Show()
}
func (this *IndexAction) RunPost(params struct {
KeyType string
Keys string
Must *actions.Must
CSRF *actionutils.CSRF
}) {
defer this.CreateLogInfo(codes.HTTPCacheTask_LogCreateHTTPCacheTaskPurge)
if len(params.Keys) == 0 {
this.Fail("请输入要刷新的Key列表")
}
// 检查Key
var realKeys = []string{}
for _, key := range strings.Split(params.Keys, "\n") {
key = strings.TrimSpace(key)
if len(key) == 0 {
continue
}
if lists.ContainsString(realKeys, key) {
continue
}
realKeys = append(realKeys, key)
}
if len(realKeys) == 0 {
this.Fail("请输入要刷新的Key列表")
}
// 校验Key
validateResp, err := this.RPC().HTTPCacheTaskKeyRPC().ValidateHTTPCacheTaskKeys(this.AdminContext(), &pb.ValidateHTTPCacheTaskKeysRequest{Keys: realKeys})
if err != nil {
this.ErrorPage(err)
return
}
var failKeyMaps = []maps.Map{}
if len(validateResp.FailKeys) > 0 {
for _, key := range validateResp.FailKeys {
failKeyMaps = append(failKeyMaps, maps.Map{
"key": key.Key,
"reason": cacheutils.KeyFailReason(key.ReasonCode),
})
}
}
this.Data["failKeys"] = failKeyMaps
if len(failKeyMaps) > 0 {
this.Fail("有" + types.String(len(failKeyMaps)) + "个Key无法完成操作请删除后重试")
}
// 提交任务
_, err = this.RPC().HTTPCacheTaskRPC().CreateHTTPCacheTask(this.AdminContext(), &pb.CreateHTTPCacheTaskRequest{
Type: "purge",
KeyType: params.KeyType,
Keys: realKeys,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,24 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/configloaders"
"github.com/TeaOSLab/EdgeAdmin/internal/web/helpers"
"github.com/iwind/TeaGo"
)
func init() {
TeaGo.BeforeStart(func(server *TeaGo.Server) {
server.
Helper(helpers.NewUserMustAuth(configloaders.AdminModuleCodeServer)).
Data("teaMenu", "servers").
Data("teaSubMenu", "cacheBatch").
Prefix("/servers/components/cache/batch").
GetPost("", new(IndexAction)).
GetPost("/fetch", new(FetchAction)).
Get("/tasks", new(TasksAction)).
GetPost("/task", new(TaskAction)).
Post("/deleteTask", new(DeleteTaskAction)).
Post("/resetTask", new(ResetTaskAction)).
EndAll()
})
}

View File

@@ -0,0 +1,27 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type ResetTaskAction struct {
actionutils.ParentAction
}
func (this *ResetTaskAction) RunPost(params struct {
TaskId int64
}) {
this.CreateLogInfo(codes.HTTPCacheTask_LogResetHTTPCacheTask, params.TaskId)
_, err := this.RPC().HTTPCacheTaskRPC().ResetHTTPCacheTask(this.AdminContext(), &pb.ResetHTTPCacheTaskRequest{HttpCacheTaskId: params.TaskId})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,137 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package cache
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/maps"
timeutil "github.com/iwind/TeaGo/utils/time"
"sort"
)
type TaskAction struct {
actionutils.ParentAction
}
func (this *TaskAction) Init() {
this.Nav("", "", "task")
}
func (this *TaskAction) RunGet(params struct {
TaskId int64
}) {
// 初始化菜单数据
err := InitMenu(this.Parent())
if err != nil {
this.ErrorPage(err)
return
}
if !this.readTask(params.TaskId) {
return
}
this.Show()
}
func (this *TaskAction) RunPost(params struct {
TaskId int64
}) {
if !this.readTask(params.TaskId) {
return
}
this.Success()
}
// 读取任务信息
func (this *TaskAction) readTask(taskId int64) (ok bool) {
taskResp, err := this.RPC().HTTPCacheTaskRPC().FindEnabledHTTPCacheTask(this.AdminContext(), &pb.FindEnabledHTTPCacheTaskRequest{HttpCacheTaskId: taskId})
if err != nil {
this.ErrorPage(err)
return
}
var task = taskResp.HttpCacheTask
if task == nil {
this.NotFound("HTTPCacheTask", taskId)
return
}
// 用户
var userMap = maps.Map{"id": 0, "username": "", "fullname": ""}
if task.User != nil {
userMap = maps.Map{
"id": task.User.Id,
"username": task.User.Username,
"fullname": task.User.Fullname,
}
}
// keys
var keyMaps = []maps.Map{}
for _, key := range task.HttpCacheTaskKeys {
// 错误信息
var errorMaps = []maps.Map{}
if len(key.ErrorsJSON) > 0 {
var m = map[int64]string{}
err = json.Unmarshal(key.ErrorsJSON, &m)
if err != nil {
this.ErrorPage(err)
return
}
for nodeId, errString := range m {
errorMaps = append(errorMaps, maps.Map{
"nodeId": nodeId,
"error": errString,
})
}
}
// 错误信息排序
if len(errorMaps) > 0 {
sort.Slice(errorMaps, func(i, j int) bool {
var m1 = errorMaps[i]
var m2 = errorMaps[j]
return m1.GetInt64("nodeId") < m2.GetInt64("nodeId")
})
}
// 集群信息
var clusterMap = maps.Map{
"id": 0,
"name": "",
}
if key.NodeCluster != nil {
clusterMap = maps.Map{
"id": key.NodeCluster.Id,
"name": key.NodeCluster.Name,
}
}
keyMaps = append(keyMaps, maps.Map{
"key": key.Key,
"isDone": key.IsDone,
"isDoing": key.IsDoing,
"errors": errorMaps,
"cluster": clusterMap,
})
}
this.Data["task"] = maps.Map{
"id": task.Id,
"type": task.Type,
"keyType": task.KeyType,
"createdTime": timeutil.FormatTime("Y-m-d H:i:s", task.CreatedAt),
"doneTime": timeutil.FormatTime("Y-m-d H:i:s", task.DoneAt),
"isDone": task.IsDone,
"isOk": task.IsOk,
"keys": keyMaps,
"user": userMap,
}
ok = true
return
}

View File

@@ -0,0 +1,73 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/maps"
timeutil "github.com/iwind/TeaGo/utils/time"
)
type TasksAction struct {
actionutils.ParentAction
}
func (this *TasksAction) Init() {
this.Nav("", "", "task")
}
func (this *TasksAction) RunGet(params struct{}) {
// 初始化菜单数据
err := InitMenu(this.Parent())
if err != nil {
this.ErrorPage(err)
return
}
// 任务数量
countResp, err := this.RPC().HTTPCacheTaskRPC().CountHTTPCacheTasks(this.AdminContext(), &pb.CountHTTPCacheTasksRequest{})
if err != nil {
this.ErrorPage(err)
return
}
var count = countResp.Count
var page = this.NewPage(count)
this.Data["page"] = page.AsHTML()
// 任务列表
var taskMaps = []maps.Map{}
tasksResp, err := this.RPC().HTTPCacheTaskRPC().ListHTTPCacheTasks(this.AdminContext(), &pb.ListHTTPCacheTasksRequest{
Offset: page.Offset,
Size: page.Size,
})
if err != nil {
this.ErrorPage(err)
return
}
for _, task := range tasksResp.HttpCacheTasks {
var userMap = maps.Map{"id": 0, "username": "", "fullname": ""}
if task.User != nil {
userMap = maps.Map{
"id": task.User.Id,
"username": task.User.Username,
"fullname": task.User.Fullname,
}
}
taskMaps = append(taskMaps, maps.Map{
"id": task.Id,
"type": task.Type,
"keyType": task.KeyType,
"isDone": task.IsDone,
"isOk": task.IsOk,
"createdTime": timeutil.FormatTime("Y-m-d H:i:s", task.CreatedAt),
"description": task.Description,
"user": userMap,
})
}
this.Data["tasks"] = taskMaps
this.Show()
}

View File

@@ -0,0 +1,24 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/rpc"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
func InitMenu(parent *actionutils.ParentAction) error {
rpcClient, err := rpc.SharedRPC()
if err != nil {
return err
}
countTasksResp, err := rpcClient.HTTPCacheTaskRPC().CountDoingHTTPCacheTasks(parent.AdminContext(), &pb.CountDoingHTTPCacheTasksRequest{})
if err != nil {
return err
}
parent.Data["countDoingTasks"] = countTasksResp.Count
return nil
}

View File

@@ -0,0 +1,56 @@
package cacheutils
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/errors"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
)
// FindCachePolicyNameWithoutError 查找缓存策略名称并忽略错误
func FindCachePolicyNameWithoutError(parent *actionutils.ParentAction, cachePolicyId int64) string {
policy, err := FindCachePolicy(parent, cachePolicyId)
if err != nil {
return ""
}
if policy == nil {
return ""
}
return policy.Name
}
// FindCachePolicy 查找缓存策略配置
func FindCachePolicy(parent *actionutils.ParentAction, cachePolicyId int64) (*serverconfigs.HTTPCachePolicy, error) {
resp, err := parent.RPC().HTTPCachePolicyRPC().FindEnabledHTTPCachePolicyConfig(parent.AdminContext(), &pb.FindEnabledHTTPCachePolicyConfigRequest{HttpCachePolicyId: cachePolicyId})
if err != nil {
return nil, err
}
if len(resp.HttpCachePolicyJSON) == 0 {
return nil, errors.New("cache policy not found")
}
var config = &serverconfigs.HTTPCachePolicy{}
err = json.Unmarshal(resp.HttpCachePolicyJSON, config)
if err != nil {
return nil, err
}
return config, nil
}
// KeyFailReason Key相关失败原因
func KeyFailReason(reasonCode string) string {
switch reasonCode {
case "requireKey":
return "空的Key"
case "requireDomain":
return "找不到Key对应的域名"
case "requireServer":
return "找不到Key对应的网站"
case "requireUser":
return "该域名不属于当前用户"
case "requireClusterId":
return "该网站没有部署到集群"
}
return "未知错误"
}

View File

@@ -0,0 +1,98 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/nodes/nodeutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/messageconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"net/http"
"strconv"
)
type CleanAction struct {
actionutils.ParentAction
}
func (this *CleanAction) Init() {
this.Nav("", "", "clean")
}
func (this *CleanAction) RunGet(params struct {
CachePolicyId int64
}) {
// 默认的集群ID
cookie, err := this.Request.Cookie("cache_cluster_id")
if cookie != nil && err == nil {
this.Data["clusterId"] = types.Int64(cookie.Value)
}
// 集群列表
clustersResp, err := this.RPC().NodeClusterRPC().FindAllEnabledNodeClustersWithHTTPCachePolicyId(this.AdminContext(), &pb.FindAllEnabledNodeClustersWithHTTPCachePolicyIdRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
clusterMaps := []maps.Map{}
for _, cluster := range clustersResp.NodeClusters {
clusterMaps = append(clusterMaps, maps.Map{
"id": cluster.Id,
"name": cluster.Name,
})
}
this.Data["clusters"] = clusterMaps
this.Show()
}
func (this *CleanAction) RunPost(params struct {
CachePolicyId int64
ClusterId int64
Must *actions.Must
}) {
// 记录clusterId
this.AddCookie(&http.Cookie{
Name: "cache_cluster_id",
Value: strconv.FormatInt(params.ClusterId, 10),
})
cachePolicyResp, err := this.RPC().HTTPCachePolicyRPC().FindEnabledHTTPCachePolicyConfig(this.AdminContext(), &pb.FindEnabledHTTPCachePolicyConfigRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
cachePolicyJSON := cachePolicyResp.HttpCachePolicyJSON
if len(cachePolicyJSON) == 0 {
this.Fail("找不到要操作的缓存策略")
}
// 发送命令
msg := &messageconfigs.CleanCacheMessage{
CachePolicyJSON: cachePolicyJSON,
}
results, err := nodeutils.SendMessageToCluster(this.AdminContext(), params.ClusterId, messageconfigs.MessageCodeCleanCache, msg, 60, false)
if err != nil {
this.ErrorPage(err)
return
}
isAllOk := true
for _, result := range results {
if !result.IsOK {
isAllOk = false
break
}
}
this.Data["isAllOk"] = isAllOk
this.Data["results"] = results
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogCleanAll, params.CachePolicyId)
this.Success()
}

View File

@@ -0,0 +1,22 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
// 计算可用缓存策略数量
type CountAction struct {
actionutils.ParentAction
}
func (this *CountAction) RunPost(params struct{}) {
countResp, err := this.RPC().HTTPCachePolicyRPC().CountAllEnabledHTTPCachePolicies(this.AdminContext(), &pb.CountAllEnabledHTTPCachePoliciesRequest{})
if err != nil {
this.ErrorPage(err)
return
}
this.Data["count"] = countResp.Count
this.Success()
}

View File

@@ -0,0 +1,142 @@
package cache
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/utils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
)
type CreatePopupAction struct {
actionutils.ParentAction
}
func (this *CreatePopupAction) Init() {
this.Nav("", "", "")
}
func (this *CreatePopupAction) RunGet(params struct{}) {
this.Data["types"] = serverconfigs.AllCachePolicyStorageTypes
this.Show()
}
func (this *CreatePopupAction) RunPost(params struct {
Name string
Type string
// file
FileDir string
FileMemoryCapacityJSON []byte
FileOpenFileCacheMax int
FileEnableSendfile bool
FileMinFreeSizeJSON []byte
CapacityJSON []byte
MaxSizeJSON []byte
FetchTimeoutJSON []byte
SyncCompressionCache bool
EnableMMAP bool
EnableIncompletePartialContent bool
Description string
IsOn bool
Must *actions.Must
}) {
params.Must.
Field("name", params.Name).
Require("请输入策略名称")
// 校验选项
var options any
switch params.Type {
case serverconfigs.CachePolicyStorageFile:
params.Must.
Field("fileDir", params.FileDir).
Require("请输入缓存目录")
var memoryCapacity = &shared.SizeCapacity{}
if len(params.FileMemoryCapacityJSON) > 0 {
err := json.Unmarshal(params.FileMemoryCapacityJSON, memoryCapacity)
if err != nil {
this.ErrorPage(err)
return
}
}
var openFileCacheConfig *serverconfigs.OpenFileCacheConfig
if params.FileOpenFileCacheMax > 0 {
openFileCacheConfig = &serverconfigs.OpenFileCacheConfig{
IsOn: true,
Max: params.FileOpenFileCacheMax,
}
}
var minFreeSize = &shared.SizeCapacity{}
var minFreeSizeJSON = params.FileMinFreeSizeJSON
if !utils.JSONIsNull(minFreeSizeJSON) {
_, err := utils.JSONDecodeConfig(minFreeSizeJSON, minFreeSize)
if err != nil {
this.ErrorPage(err)
return
}
if minFreeSize.Count < 0 {
minFreeSize.Count = 0
}
}
options = &serverconfigs.HTTPFileCacheStorage{
Dir: params.FileDir,
MemoryPolicy: &serverconfigs.HTTPCachePolicy{
Capacity: memoryCapacity,
},
OpenFileCache: openFileCacheConfig,
EnableSendfile: params.FileEnableSendfile,
MinFreeSize: minFreeSize,
EnableMMAP: params.EnableMMAP,
EnableIncompletePartialContent: params.EnableIncompletePartialContent,
}
case serverconfigs.CachePolicyStorageMemory:
options = &serverconfigs.HTTPMemoryCacheStorage{}
default:
this.Fail("请选择正确的缓存类型")
}
optionsJSON, err := json.Marshal(options)
if err != nil {
this.ErrorPage(err)
return
}
createResp, err := this.RPC().HTTPCachePolicyRPC().CreateHTTPCachePolicy(this.AdminContext(), &pb.CreateHTTPCachePolicyRequest{
IsOn: params.IsOn,
Name: params.Name,
Description: params.Description,
CapacityJSON: params.CapacityJSON,
MaxSizeJSON: params.MaxSizeJSON,
FetchTimeoutJSON: params.FetchTimeoutJSON,
Type: params.Type,
OptionsJSON: optionsJSON,
SyncCompressionCache: params.SyncCompressionCache,
})
if err != nil {
this.ErrorPage(err)
return
}
// 返回数据
this.Data["cachePolicy"] = maps.Map{
"id": createResp.HttpCachePolicyId,
"name": params.Name,
}
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogCreateCachePolicy, createResp.HttpCachePolicyId)
this.Success()
}

View File

@@ -0,0 +1,36 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type DeleteAction struct {
actionutils.ParentAction
}
func (this *DeleteAction) RunPost(params struct {
CachePolicyId int64
}) {
// 检查是否被引用
countResp, err := this.RPC().NodeClusterRPC().CountAllEnabledNodeClustersWithHTTPCachePolicyId(this.AdminContext(), &pb.CountAllEnabledNodeClustersWithHTTPCachePolicyIdRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
if countResp.Count > 0 {
this.Fail("此缓存策略正在被有些集群引用,请修改后再删除。")
}
_, err = this.RPC().HTTPCachePolicyRPC().DeleteHTTPCachePolicy(this.AdminContext(), &pb.DeleteHTTPCachePolicyRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogDeleteCachePolicy, params.CachePolicyId)
this.Success()
}

View File

@@ -0,0 +1,128 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/cache/cacheutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"net/http"
"strconv"
"strings"
)
type FetchAction struct {
actionutils.ParentAction
}
func (this *FetchAction) Init() {
this.Nav("", "", "fetch")
}
func (this *FetchAction) RunGet(params struct {
CachePolicyId int64
}) {
// 默认的集群ID
cookie, err := this.Request.Cookie("cache_cluster_id")
if cookie != nil && err == nil {
this.Data["clusterId"] = types.Int64(cookie.Value)
}
// 集群列表
clustersResp, err := this.RPC().NodeClusterRPC().FindAllEnabledNodeClustersWithHTTPCachePolicyId(this.AdminContext(), &pb.FindAllEnabledNodeClustersWithHTTPCachePolicyIdRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
clusterMaps := []maps.Map{}
for _, cluster := range clustersResp.NodeClusters {
clusterMaps = append(clusterMaps, maps.Map{
"id": cluster.Id,
"name": cluster.Name,
})
}
this.Data["clusters"] = clusterMaps
this.Show()
}
func (this *FetchAction) RunPost(params struct {
CachePolicyId int64
ClusterId int64
Keys string
Must *actions.Must
}) {
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogFetchCaches, params.CachePolicyId)
// 记录clusterId
this.AddCookie(&http.Cookie{
Name: "cache_cluster_id",
Value: strconv.FormatInt(params.ClusterId, 10),
})
cachePolicyResp, err := this.RPC().HTTPCachePolicyRPC().FindEnabledHTTPCachePolicyConfig(this.AdminContext(), &pb.FindEnabledHTTPCachePolicyConfigRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
cachePolicyJSON := cachePolicyResp.HttpCachePolicyJSON
if len(cachePolicyJSON) == 0 {
this.Fail("找不到要操作的缓存策略")
}
if len(params.Keys) == 0 {
this.Fail("请输入要预热的Key列表")
}
realKeys := []string{}
for _, key := range strings.Split(params.Keys, "\n") {
key = strings.TrimSpace(key)
if len(key) == 0 {
continue
}
if lists.ContainsString(realKeys, key) {
continue
}
realKeys = append(realKeys, key)
}
// 校验Key
// 这里暂时不校验服务ID
validateResp, err := this.RPC().HTTPCacheTaskKeyRPC().ValidateHTTPCacheTaskKeys(this.AdminContext(), &pb.ValidateHTTPCacheTaskKeysRequest{Keys: realKeys})
if err != nil {
this.ErrorPage(err)
return
}
var failKeyMaps = []maps.Map{}
if len(validateResp.FailKeys) > 0 {
for _, key := range validateResp.FailKeys {
failKeyMaps = append(failKeyMaps, maps.Map{
"key": key.Key,
"reason": cacheutils.KeyFailReason(key.ReasonCode),
})
}
}
this.Data["failKeys"] = failKeyMaps
if len(failKeyMaps) > 0 {
this.Fail("有" + types.String(len(failKeyMaps)) + "个Key无法完成操作请删除后重试")
}
// 提交任务
_, err = this.RPC().HTTPCacheTaskRPC().CreateHTTPCacheTask(this.AdminContext(), &pb.CreateHTTPCacheTaskRequest{
Type: "fetch",
KeyType: "key",
Keys: realKeys,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,36 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/cache/cacheutils"
"github.com/iwind/TeaGo/actions"
"net/http"
)
type Helper struct {
}
func NewHelper() *Helper {
return &Helper{}
}
func (this *Helper) BeforeAction(actionPtr actions.ActionWrapper) {
action := actionPtr.Object()
if action.Request.Method != http.MethodGet {
return
}
action.Data["mainTab"] = "component"
action.Data["secondMenuItem"] = "cache"
cachePolicyId := action.ParamInt64("cachePolicyId")
action.Data["cachePolicyId"] = cachePolicyId
parentActionObj, ok := actionPtr.(interface {
Parent() *actionutils.ParentAction
})
if ok {
var parentAction = parentActionObj.Parent()
action.Data["cachePolicyName"] = cacheutils.FindCachePolicyNameWithoutError(parentAction, cachePolicyId)
}
}

View File

@@ -0,0 +1,81 @@
package cache
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/iwind/TeaGo/maps"
)
type IndexAction struct {
actionutils.ParentAction
}
func (this *IndexAction) Init() {
this.FirstMenu("index")
}
func (this *IndexAction) RunGet(params struct {
ClusterId int64
Keyword string
StorageType string
}) {
this.Data["keyword"] = params.Keyword
this.Data["clusterId"] = params.ClusterId
this.Data["storageType"] = params.StorageType
countResp, err := this.RPC().HTTPCachePolicyRPC().CountAllEnabledHTTPCachePolicies(this.AdminContext(), &pb.CountAllEnabledHTTPCachePoliciesRequest{
NodeClusterId: params.ClusterId,
Keyword: params.Keyword,
Type: params.StorageType,
})
if err != nil {
this.ErrorPage(err)
return
}
count := countResp.Count
page := this.NewPage(count)
this.Data["page"] = page.AsHTML()
listResp, err := this.RPC().HTTPCachePolicyRPC().ListEnabledHTTPCachePolicies(this.AdminContext(), &pb.ListEnabledHTTPCachePoliciesRequest{
Keyword: params.Keyword,
NodeClusterId: params.ClusterId,
Type: params.StorageType,
Offset: page.Offset,
Size: page.Size,
})
if err != nil {
this.ErrorPage(err)
return
}
cachePoliciesJSON := listResp.HttpCachePoliciesJSON
cachePolicies := []*serverconfigs.HTTPCachePolicy{}
err = json.Unmarshal(cachePoliciesJSON, &cachePolicies)
if err != nil {
this.ErrorPage(err)
return
}
this.Data["cachePolicies"] = cachePolicies
infos := []maps.Map{}
for _, cachePolicy := range cachePolicies {
countClustersResp, err := this.RPC().NodeClusterRPC().CountAllEnabledNodeClustersWithHTTPCachePolicyId(this.AdminContext(), &pb.CountAllEnabledNodeClustersWithHTTPCachePolicyIdRequest{HttpCachePolicyId: cachePolicy.Id})
if err != nil {
this.ErrorPage(err)
return
}
countClusters := countClustersResp.Count
infos = append(infos, maps.Map{
"typeName": serverconfigs.FindCachePolicyStorageName(cachePolicy.Type),
"countClusters": countClusters,
})
}
this.Data["infos"] = infos
// 所有的存储类型
this.Data["storageTypes"] = serverconfigs.AllCachePolicyStorageTypes
this.Show()
}

View File

@@ -0,0 +1,34 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/configloaders"
"github.com/TeaOSLab/EdgeAdmin/internal/web/helpers"
"github.com/iwind/TeaGo"
)
func init() {
TeaGo.BeforeStart(func(server *TeaGo.Server) {
server.
Helper(helpers.NewUserMustAuth(configloaders.AdminModuleCodeServer)).
Helper(NewHelper()).
Data("teaMenu", "servers").
Data("teaSubMenu", "cache").
Prefix("/servers/components/cache").
Get("", new(IndexAction)).
GetPost("/createPopup", new(CreatePopupAction)).
Get("/policy", new(PolicyAction)).
GetPost("/update", new(UpdateAction)).
GetPost("/clean", new(CleanAction)).
GetPost("/fetch", new(FetchAction)).
GetPost("/purge", new(PurgeAction)).
GetPost("/stat", new(StatAction)).
GetPost("/test", new(TestAction)).
Post("/delete", new(DeleteAction)).
Post("/testRead", new(TestReadAction)).
Post("/testWrite", new(TestWriteAction)).
Get("/selectPopup", new(SelectPopupAction)).
Post("/count", new(CountAction)).
Post("/updateRefs", new(UpdateRefsAction)).
EndAll()
})
}

View File

@@ -0,0 +1,53 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/cache/cacheutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/iwind/TeaGo/maps"
)
type PolicyAction struct {
actionutils.ParentAction
}
func (this *PolicyAction) Init() {
this.Nav("", "", "index")
}
func (this *PolicyAction) RunGet(params struct {
CachePolicyId int64
}) {
cachePolicy, err := cacheutils.FindCachePolicy(this.Parent(), params.CachePolicyId)
if err != nil {
this.ErrorPage(err)
return
}
this.Data["cachePolicy"] = cachePolicy
// 预热超时时间
this.Data["fetchTimeoutString"] = ""
if cachePolicy.FetchTimeout != nil && cachePolicy.FetchTimeout.Count > 0 {
this.Data["fetchTimeoutString"] = cachePolicy.FetchTimeout.Description()
}
this.Data["typeName"] = serverconfigs.FindCachePolicyStorageName(cachePolicy.Type)
// 正在使用此策略的集群
clustersResp, err := this.RPC().NodeClusterRPC().FindAllEnabledNodeClustersWithHTTPCachePolicyId(this.AdminContext(), &pb.FindAllEnabledNodeClustersWithHTTPCachePolicyIdRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
var clusterMaps = []maps.Map{}
for _, cluster := range clustersResp.NodeClusters {
clusterMaps = append(clusterMaps, maps.Map{
"id": cluster.Id,
"name": cluster.Name,
})
}
this.Data["clusters"] = clusterMaps
this.Show()
}

View File

@@ -0,0 +1,126 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/cache/cacheutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"net/http"
"strconv"
"strings"
)
type PurgeAction struct {
actionutils.ParentAction
}
func (this *PurgeAction) Init() {
this.Nav("", "", "purge")
}
func (this *PurgeAction) RunGet(params struct {
CachePolicyId int64
}) {
// 默认的集群ID
cookie, err := this.Request.Cookie("cache_cluster_id")
if cookie != nil && err == nil {
this.Data["clusterId"] = types.Int64(cookie.Value)
}
// 集群列表
clustersResp, err := this.RPC().NodeClusterRPC().FindAllEnabledNodeClustersWithHTTPCachePolicyId(this.AdminContext(), &pb.FindAllEnabledNodeClustersWithHTTPCachePolicyIdRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
clusterMaps := []maps.Map{}
for _, cluster := range clustersResp.NodeClusters {
clusterMaps = append(clusterMaps, maps.Map{
"id": cluster.Id,
"name": cluster.Name,
})
}
this.Data["clusters"] = clusterMaps
this.Show()
}
func (this *PurgeAction) RunPost(params struct {
CachePolicyId int64
ClusterId int64
KeyType string
Keys string
Must *actions.Must
}) {
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogPurgeCaches, params.CachePolicyId)
// 记录clusterId
this.AddCookie(&http.Cookie{
Name: "cache_cluster_id",
Value: strconv.FormatInt(params.ClusterId, 10),
})
cachePolicyResp, err := this.RPC().HTTPCachePolicyRPC().FindEnabledHTTPCachePolicyConfig(this.AdminContext(), &pb.FindEnabledHTTPCachePolicyConfigRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
cachePolicyJSON := cachePolicyResp.HttpCachePolicyJSON
if len(cachePolicyJSON) == 0 {
this.Fail("找不到要操作的缓存策略")
}
if len(params.Keys) == 0 {
this.Fail("请输入要删除的Key列表")
}
realKeys := []string{}
for _, key := range strings.Split(params.Keys, "\n") {
key = strings.TrimSpace(key)
if len(key) == 0 {
continue
}
if lists.ContainsString(realKeys, key) {
continue
}
realKeys = append(realKeys, key)
}
// 校验Key
validateResp, err := this.RPC().HTTPCacheTaskKeyRPC().ValidateHTTPCacheTaskKeys(this.AdminContext(), &pb.ValidateHTTPCacheTaskKeysRequest{Keys: realKeys})
if err != nil {
this.ErrorPage(err)
return
}
var failKeyMaps = []maps.Map{}
if len(validateResp.FailKeys) > 0 {
for _, key := range validateResp.FailKeys {
failKeyMaps = append(failKeyMaps, maps.Map{
"key": key.Key,
"reason": cacheutils.KeyFailReason(key.ReasonCode),
})
}
}
this.Data["failKeys"] = failKeyMaps
if len(failKeyMaps) > 0 {
this.Fail("有" + types.String(len(failKeyMaps)) + "个Key无法完成操作请删除后重试")
}
// 提交任务
_, err = this.RPC().HTTPCacheTaskRPC().CreateHTTPCacheTask(this.AdminContext(), &pb.CreateHTTPCacheTaskRequest{
Type: "purge",
KeyType: params.KeyType,
Keys: realKeys,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,60 @@
package cache
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/iwind/TeaGo/maps"
)
type SelectPopupAction struct {
actionutils.ParentAction
}
func (this *SelectPopupAction) Init() {
this.Nav("", "", "")
}
func (this *SelectPopupAction) RunGet(params struct{}) {
countResp, err := this.RPC().HTTPCachePolicyRPC().CountAllEnabledHTTPCachePolicies(this.AdminContext(), &pb.CountAllEnabledHTTPCachePoliciesRequest{})
if err != nil {
this.ErrorPage(err)
return
}
count := countResp.Count
page := this.NewPage(count)
this.Data["page"] = page.AsHTML()
cachePoliciesResp, err := this.RPC().HTTPCachePolicyRPC().ListEnabledHTTPCachePolicies(this.AdminContext(), &pb.ListEnabledHTTPCachePoliciesRequest{
Offset: page.Offset,
Size: page.Size,
})
if err != nil {
this.ErrorPage(err)
return
}
cachePolicies := []*serverconfigs.HTTPCachePolicy{}
if len(cachePoliciesResp.HttpCachePoliciesJSON) > 0 {
err = json.Unmarshal(cachePoliciesResp.HttpCachePoliciesJSON, &cachePolicies)
if err != nil {
this.ErrorPage(err)
return
}
}
policyMaps := []maps.Map{}
for _, cachePolicy := range cachePolicies {
policyMaps = append(policyMaps, maps.Map{
"id": cachePolicy.Id,
"name": cachePolicy.Name,
"description": cachePolicy.Description,
"isOn": cachePolicy.IsOn,
})
}
this.Data["cachePolicies"] = policyMaps
this.Show()
}

View File

@@ -0,0 +1,98 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/nodes/nodeutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/messageconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"net/http"
"strconv"
)
type StatAction struct {
actionutils.ParentAction
}
func (this *StatAction) Init() {
this.Nav("", "", "stat")
}
func (this *StatAction) RunGet(params struct {
CachePolicyId int64
}) {
// 默认的集群ID
cookie, err := this.Request.Cookie("cache_cluster_id")
if cookie != nil && err == nil {
this.Data["clusterId"] = types.Int64(cookie.Value)
}
// 集群列表
clustersResp, err := this.RPC().NodeClusterRPC().FindAllEnabledNodeClustersWithHTTPCachePolicyId(this.AdminContext(), &pb.FindAllEnabledNodeClustersWithHTTPCachePolicyIdRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
clusterMaps := []maps.Map{}
for _, cluster := range clustersResp.NodeClusters {
clusterMaps = append(clusterMaps, maps.Map{
"id": cluster.Id,
"name": cluster.Name,
})
}
this.Data["clusters"] = clusterMaps
this.Show()
}
func (this *StatAction) RunPost(params struct {
CachePolicyId int64
ClusterId int64
Must *actions.Must
}) {
// 记录clusterId
this.AddCookie(&http.Cookie{
Name: "cache_cluster_id",
Value: strconv.FormatInt(params.ClusterId, 10),
})
cachePolicyResp, err := this.RPC().HTTPCachePolicyRPC().FindEnabledHTTPCachePolicyConfig(this.AdminContext(), &pb.FindEnabledHTTPCachePolicyConfigRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
cachePolicyJSON := cachePolicyResp.HttpCachePolicyJSON
if len(cachePolicyJSON) == 0 {
this.Fail("找不到要操作的缓存策略")
}
// 发送命令
msg := &messageconfigs.StatCacheMessage{
CachePolicyJSON: cachePolicyJSON,
}
results, err := nodeutils.SendMessageToCluster(this.AdminContext(), params.ClusterId, messageconfigs.MessageCodeStatCache, msg, 10, false)
if err != nil {
this.ErrorPage(err)
return
}
isAllOk := true
for _, result := range results {
if !result.IsOK {
isAllOk = false
break
}
}
this.Data["isAllOk"] = isAllOk
this.Data["results"] = results
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogStatCaches, params.CachePolicyId)
this.Success()
}

View File

@@ -0,0 +1,43 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
)
type TestAction struct {
actionutils.ParentAction
}
func (this *TestAction) Init() {
this.Nav("", "", "test")
}
func (this *TestAction) RunGet(params struct {
CachePolicyId int64
}) {
// 默认的集群ID
cookie, err := this.Request.Cookie("cache_cluster_id")
if cookie != nil && err == nil {
this.Data["clusterId"] = types.Int64(cookie.Value)
}
// 集群列表
clustersResp, err := this.RPC().NodeClusterRPC().FindAllEnabledNodeClustersWithHTTPCachePolicyId(this.AdminContext(), &pb.FindAllEnabledNodeClustersWithHTTPCachePolicyIdRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
clusterMaps := []maps.Map{}
for _, cluster := range clustersResp.NodeClusters {
clusterMaps = append(clusterMaps, maps.Map{
"id": cluster.Id,
"name": cluster.Name,
})
}
this.Data["clusters"] = clusterMaps
this.Show()
}

View File

@@ -0,0 +1,64 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/nodes/nodeutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/messageconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"net/http"
"strconv"
)
type TestReadAction struct {
actionutils.ParentAction
}
func (this *TestReadAction) RunPost(params struct {
ClusterId int64
CachePolicyId int64
Key string
}) {
// 记录clusterId
this.AddCookie(&http.Cookie{
Name: "cache_cluster_id",
Value: strconv.FormatInt(params.ClusterId, 10),
})
cachePolicyResp, err := this.RPC().HTTPCachePolicyRPC().FindEnabledHTTPCachePolicyConfig(this.AdminContext(), &pb.FindEnabledHTTPCachePolicyConfigRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
cachePolicyJSON := cachePolicyResp.HttpCachePolicyJSON
if len(cachePolicyJSON) == 0 {
this.Fail("找不到要操作的缓存策略")
}
// 发送命令
msg := &messageconfigs.ReadCacheMessage{
CachePolicyJSON: cachePolicyJSON,
Key: params.Key,
}
results, err := nodeutils.SendMessageToCluster(this.AdminContext(), params.ClusterId, messageconfigs.MessageCodeReadCache, msg, 10, false)
if err != nil {
this.ErrorPage(err)
return
}
isAllOk := true
for _, result := range results {
if !result.IsOK {
isAllOk = false
break
}
}
this.Data["isAllOk"] = isAllOk
this.Data["results"] = results
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogTestReading, params.CachePolicyId)
this.Success()
}

View File

@@ -0,0 +1,67 @@
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/nodes/nodeutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/messageconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"net/http"
"strconv"
)
type TestWriteAction struct {
actionutils.ParentAction
}
func (this *TestWriteAction) RunPost(params struct {
ClusterId int64
CachePolicyId int64
Key string
Value string
}) {
// 记录clusterId
this.AddCookie(&http.Cookie{
Name: "cache_cluster_id",
Value: strconv.FormatInt(params.ClusterId, 10),
})
cachePolicyResp, err := this.RPC().HTTPCachePolicyRPC().FindEnabledHTTPCachePolicyConfig(this.AdminContext(), &pb.FindEnabledHTTPCachePolicyConfigRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
cachePolicyJSON := cachePolicyResp.HttpCachePolicyJSON
if len(cachePolicyJSON) == 0 {
this.Fail("找不到要操作的缓存策略")
}
// 发送命令
msg := &messageconfigs.WriteCacheMessage{
CachePolicyJSON: cachePolicyJSON,
Key: params.Key,
Value: []byte(params.Value),
LifeSeconds: 3600,
}
results, err := nodeutils.SendMessageToCluster(this.AdminContext(), params.ClusterId, messageconfigs.MessageCodeWriteCache, msg, 10, false)
if err != nil {
this.ErrorPage(err)
return
}
isAllOk := true
for _, result := range results {
if !result.IsOK {
isAllOk = false
break
}
}
this.Data["isAllOk"] = isAllOk
this.Data["results"] = results
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogTestWriting, params.CachePolicyId)
this.Success()
}

View File

@@ -0,0 +1,219 @@
package cache
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/utils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"github.com/iwind/TeaGo/actions"
)
type UpdateAction struct {
actionutils.ParentAction
}
func (this *UpdateAction) Init() {
this.Nav("", "", "update")
}
func (this *UpdateAction) RunGet(params struct {
CachePolicyId int64
}) {
configResp, err := this.RPC().HTTPCachePolicyRPC().FindEnabledHTTPCachePolicyConfig(this.AdminContext(), &pb.FindEnabledHTTPCachePolicyConfigRequest{HttpCachePolicyId: params.CachePolicyId})
if err != nil {
this.ErrorPage(err)
return
}
var configJSON = configResp.HttpCachePolicyJSON
if len(configJSON) == 0 {
this.NotFound("cachePolicy", params.CachePolicyId)
return
}
var cachePolicy = &serverconfigs.HTTPCachePolicy{}
err = json.Unmarshal(configJSON, cachePolicy)
if err != nil {
this.ErrorPage(err)
return
}
if cachePolicy.Type == serverconfigs.CachePolicyStorageFile && cachePolicy.Options != nil {
// fix min free size
{
_, ok := cachePolicy.Options["minFreeSize"]
if !ok {
cachePolicy.Options["minFreeSize"] = &shared.SizeCapacity{
Count: 0,
Unit: shared.SizeCapacityUnitGB,
}
}
}
// fix enableMMAP
{
_, ok := cachePolicy.Options["enableMMAP"]
if !ok {
cachePolicy.Options["enableMMAP"] = false
}
}
// fix enableIncompletePartialContent
{
_, ok := cachePolicy.Options["enableIncompletePartialContent"]
if !ok {
cachePolicy.Options["enableIncompletePartialContent"] = true
}
}
}
this.Data["cachePolicy"] = cachePolicy
// 其他选项
this.Data["types"] = serverconfigs.AllCachePolicyStorageTypes
this.Show()
}
func (this *UpdateAction) RunPost(params struct {
CachePolicyId int64
Name string
Type string
// file
FileDir string
FileMemoryCapacityJSON []byte
FileOpenFileCacheMax int
FileEnableSendfile bool
FileMinFreeSizeJSON []byte
CapacityJSON []byte
MaxSizeJSON []byte
SyncCompressionCache bool
FetchTimeoutJSON []byte
EnableMMAP bool
EnableIncompletePartialContent bool
Description string
IsOn bool
RefsJSON []byte
Must *actions.Must
}) {
// 创建日志
defer this.CreateLogInfo(codes.ServerCachePolicy_LogUpdateCachePolicy, params.CachePolicyId)
params.Must.
Field("name", params.Name).
Require("请输入策略名称")
// 校验选项
var options interface{}
switch params.Type {
case serverconfigs.CachePolicyStorageFile:
params.Must.
Field("fileDir", params.FileDir).
Require("请输入缓存目录")
var memoryCapacity = &shared.SizeCapacity{}
if len(params.FileMemoryCapacityJSON) > 0 {
err := json.Unmarshal(params.FileMemoryCapacityJSON, memoryCapacity)
if err != nil {
this.ErrorPage(err)
return
}
}
var openFileCacheConfig *serverconfigs.OpenFileCacheConfig
if params.FileOpenFileCacheMax > 0 {
openFileCacheConfig = &serverconfigs.OpenFileCacheConfig{
IsOn: true,
Max: params.FileOpenFileCacheMax,
}
}
var minFreeSize = &shared.SizeCapacity{}
var minFreeSizeJSON = params.FileMinFreeSizeJSON
if !utils.JSONIsNull(minFreeSizeJSON) {
_, err := utils.JSONDecodeConfig(minFreeSizeJSON, minFreeSize)
if err != nil {
this.ErrorPage(err)
return
}
if minFreeSize.Count < 0 {
minFreeSize.Count = 0
}
}
options = &serverconfigs.HTTPFileCacheStorage{
Dir: params.FileDir,
MemoryPolicy: &serverconfigs.HTTPCachePolicy{
Capacity: memoryCapacity,
},
OpenFileCache: openFileCacheConfig,
EnableSendfile: params.FileEnableSendfile,
MinFreeSize: minFreeSize,
EnableMMAP: params.EnableMMAP,
EnableIncompletePartialContent: params.EnableIncompletePartialContent,
}
case serverconfigs.CachePolicyStorageMemory:
options = &serverconfigs.HTTPMemoryCacheStorage{}
default:
this.Fail("请选择正确的缓存类型")
}
optionsJSON, err := json.Marshal(options)
if err != nil {
this.ErrorPage(err)
return
}
// 校验缓存条件
var refs = []*serverconfigs.HTTPCacheRef{}
if len(params.RefsJSON) > 0 {
err = json.Unmarshal(params.RefsJSON, &refs)
if err != nil {
this.Fail("缓存条件解析失败:" + err.Error())
}
for _, ref := range refs {
err = ref.Init()
if err != nil {
this.Fail("缓存条件校验失败:" + err.Error())
}
}
}
_, err = this.RPC().HTTPCachePolicyRPC().UpdateHTTPCachePolicy(this.AdminContext(), &pb.UpdateHTTPCachePolicyRequest{
HttpCachePolicyId: params.CachePolicyId,
IsOn: params.IsOn,
Name: params.Name,
Description: params.Description,
CapacityJSON: params.CapacityJSON,
MaxSizeJSON: params.MaxSizeJSON,
Type: params.Type,
OptionsJSON: optionsJSON,
SyncCompressionCache: params.SyncCompressionCache,
FetchTimeoutJSON: params.FetchTimeoutJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
// 修改缓存条件
_, err = this.RPC().HTTPCachePolicyRPC().UpdateHTTPCachePolicyRefs(this.AdminContext(), &pb.UpdateHTTPCachePolicyRefsRequest{
HttpCachePolicyId: params.CachePolicyId,
RefsJSON: params.RefsJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,35 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package cache
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type UpdateRefsAction struct {
actionutils.ParentAction
}
func (this *UpdateRefsAction) Init() {
this.Nav("", "", "")
}
func (this *UpdateRefsAction) RunPost(params struct {
CachePolicyId int64
RefsJSON []byte
}) {
// 修改缓存条件
if params.CachePolicyId > 0 && len(params.RefsJSON) > 0 {
_, err := this.RPC().HTTPCachePolicyRPC().UpdateHTTPCachePolicyRefs(this.AdminContext(), &pb.UpdateHTTPCachePolicyRefsRequest{
HttpCachePolicyId: params.CachePolicyId,
RefsJSON: params.RefsJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
}
this.Success()
}

View File

@@ -0,0 +1,22 @@
package log
import (
"github.com/iwind/TeaGo/actions"
"net/http"
)
type Helper struct {
}
func NewHelper() *Helper {
return &Helper{}
}
func (this *Helper) BeforeAction(action *actions.ActionObject) {
if action.Request.Method != http.MethodGet {
return
}
action.Data["mainTab"] = "component"
action.Data["secondMenuItem"] = "log"
}

View File

@@ -0,0 +1,18 @@
package log
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
)
type IndexAction struct {
actionutils.ParentAction
}
func (this *IndexAction) Init() {
this.FirstMenu("index")
}
func (this *IndexAction) RunGet(params struct{}) {
this.Show()
}

View File

@@ -0,0 +1,18 @@
package log
import (
"github.com/TeaOSLab/EdgeAdmin/internal/configloaders"
"github.com/TeaOSLab/EdgeAdmin/internal/web/helpers"
"github.com/iwind/TeaGo"
)
func init() {
TeaGo.BeforeStart(func(server *TeaGo.Server) {
server.
Helper(helpers.NewUserMustAuth(configloaders.AdminModuleCodeServer)).
Helper(NewHelper()).
Prefix("/servers/components/log").
Get("", new(IndexAction)).
EndAll()
})
}

View File

@@ -0,0 +1,21 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type CountAction struct {
actionutils.ParentAction
}
func (this *CountAction) RunPost(params struct{}) {
countResp, err := this.RPC().HTTPFirewallPolicyRPC().CountAllEnabledHTTPFirewallPolicies(this.AdminContext(), &pb.CountAllEnabledHTTPFirewallPoliciesRequest{})
if err != nil {
this.ErrorPage(err)
return
}
this.Data["count"] = countResp.Count
this.Success()
}

View File

@@ -0,0 +1,104 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
)
type CreateGroupPopupAction struct {
actionutils.ParentAction
}
func (this *CreateGroupPopupAction) Init() {
this.Nav("", "", "")
}
func (this *CreateGroupPopupAction) RunGet(params struct {
Type string
}) {
this.Data["type"] = params.Type
this.Show()
}
func (this *CreateGroupPopupAction) RunPost(params struct {
FirewallPolicyId int64
Type string
Name string
Code string
Description string
IsOn bool
Must *actions.Must
}) {
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
}
params.Must.
Field("name", params.Name).
Require("请输入分组名称")
createResp, err := this.RPC().HTTPFirewallRuleGroupRPC().CreateHTTPFirewallRuleGroup(this.AdminContext(), &pb.CreateHTTPFirewallRuleGroupRequest{
IsOn: params.IsOn,
Name: params.Name,
Code: params.Code,
Description: params.Description,
})
if err != nil {
this.ErrorPage(err)
return
}
groupId := createResp.FirewallRuleGroupId
switch params.Type {
case "inbound":
firewallPolicy.Inbound.GroupRefs = append(firewallPolicy.Inbound.GroupRefs, &firewallconfigs.HTTPFirewallRuleGroupRef{
IsOn: true,
GroupId: groupId,
})
default:
firewallPolicy.Outbound.GroupRefs = append(firewallPolicy.Outbound.GroupRefs, &firewallconfigs.HTTPFirewallRuleGroupRef{
IsOn: true,
GroupId: groupId,
})
}
inboundJSON, err := firewallPolicy.InboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
outboundJSON, err := firewallPolicy.OutboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallPolicyRPC().UpdateHTTPFirewallPolicyGroups(this.AdminContext(), &pb.UpdateHTTPFirewallPolicyGroupsRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
InboundJSON: inboundJSON,
OutboundJSON: outboundJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
// 日志
defer this.CreateLogInfo(codes.WAFRuleGroup_LogCreateRuleGroup, groupId, params.Name)
this.Success()
}

View File

@@ -0,0 +1,70 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
)
type CreatePopupAction struct {
actionutils.ParentAction
}
func (this *CreatePopupAction) Init() {
this.Nav("", "", "")
}
func (this *CreatePopupAction) RunGet(params struct{}) {
// 预置分组
groups := []maps.Map{}
templatePolicy := firewallconfigs.HTTPFirewallTemplate()
for _, group := range templatePolicy.AllRuleGroups() {
groups = append(groups, maps.Map{
"code": group.Code,
"name": group.Name,
"isOn": group.IsOn,
})
}
this.Data["groups"] = groups
this.Show()
}
func (this *CreatePopupAction) RunPost(params struct {
Name string
GroupCodes []string
Description string
IsOn bool
Must *actions.Must
}) {
params.Must.
Field("name", params.Name).
Require("请输入策略名称")
createResp, err := this.RPC().HTTPFirewallPolicyRPC().CreateHTTPFirewallPolicy(this.AdminContext(), &pb.CreateHTTPFirewallPolicyRequest{
IsOn: params.IsOn,
Name: params.Name,
Description: params.Description,
HttpFirewallGroupCodes: params.GroupCodes,
})
if err != nil {
this.ErrorPage(err)
return
}
// 返回数据
this.Data["firewallPolicy"] = maps.Map{
"id": createResp.HttpFirewallPolicyId,
"name": params.Name,
"description": params.Description,
}
// 日志
defer this.CreateLogInfo(codes.WAFPolicy_LogCreateWAFPolicy, createResp.HttpFirewallPolicyId)
this.Success()
}

View File

@@ -0,0 +1,126 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
)
type CreateRulePopupAction struct {
actionutils.ParentAction
}
func (this *CreateRulePopupAction) Init() {
this.Nav("", "", "")
}
func (this *CreateRulePopupAction) RunGet(params struct {
Type string
}) {
// check points
var checkpointList = []maps.Map{}
for _, checkpoint := range firewallconfigs.AllCheckpoints {
if (params.Type == "inbound" && checkpoint.IsRequest) || params.Type == "outbound" {
checkpointList = append(checkpointList, maps.Map{
"name": checkpoint.Name,
"prefix": checkpoint.Prefix,
"description": checkpoint.Description,
"hasParams": checkpoint.HasParams,
"params": checkpoint.Params,
"options": checkpoint.Options,
"isComposed": checkpoint.IsComposed,
"dataType": checkpoint.DataType,
})
}
}
// operators
var operatorMaps = []maps.Map{}
for _, operator := range firewallconfigs.AllRuleOperators {
operatorMaps = append(operatorMaps, maps.Map{
"name": operator.Name,
"code": operator.Code,
"description": operator.Description,
"case": operator.CaseInsensitive,
"dataType": operator.DataType,
})
}
this.Data["operators"] = operatorMaps
this.Data["checkpoints"] = checkpointList
this.Show()
}
func (this *CreateRulePopupAction) RunPost(params struct {
RuleId int64
Prefix string
Operator string
Param string
ParamFiltersJSON []byte
OptionsJSON []byte
Value string
Case bool
Description string
Must *actions.Must
}) {
params.Must.
Field("prefix", params.Prefix).
Require("请选择参数")
if len(params.Value) > 4096 {
this.FailField("value", "对比值内容长度不能超过4096个字符")
return
}
var rule = &firewallconfigs.HTTPFirewallRule{
Id: params.RuleId,
IsOn: true,
}
if len(params.Param) > 0 {
rule.Param = "${" + params.Prefix + "." + params.Param + "}"
} else {
rule.Param = "${" + params.Prefix + "}"
}
var paramFilters = []*firewallconfigs.ParamFilter{}
if len(params.ParamFiltersJSON) > 0 {
err := json.Unmarshal(params.ParamFiltersJSON, &paramFilters)
if err != nil {
this.ErrorPage(err)
return
}
}
rule.ParamFilters = paramFilters
rule.Operator = params.Operator
rule.Value = params.Value
rule.IsCaseInsensitive = params.Case
rule.Description = params.Description
if len(params.OptionsJSON) > 0 {
options := []maps.Map{}
err := json.Unmarshal(params.OptionsJSON, &options)
if err != nil {
this.ErrorPage(err)
return
}
rule.CheckpointOptions = map[string]interface{}{}
for _, option := range options {
rule.CheckpointOptions[option.GetString("code")] = option.Get("value")
}
}
// 校验
err := rule.Init()
if err != nil {
this.Fail("校验规则 '" + rule.Param + " " + rule.Operator + " " + rule.Value + "' 失败,原因:" + err.Error())
}
this.Data["rule"] = rule
this.Success()
}

View File

@@ -0,0 +1,231 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
"strconv"
)
type CreateSetPopupAction struct {
actionutils.ParentAction
}
func (this *CreateSetPopupAction) Init() {
this.Nav("", "", "")
}
func (this *CreateSetPopupAction) RunGet(params struct {
FirewallPolicyId int64
GroupId int64
Type string
}) {
this.Data["groupId"] = params.GroupId
this.Data["type"] = params.Type
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
this.Data["firewallPolicy"] = firewallPolicy
// 一些配置
this.Data["connectors"] = []maps.Map{
{
"name": this.Lang(codes.WAF_ConnectorAnd),
"value": firewallconfigs.HTTPFirewallRuleConnectorAnd,
"description": this.Lang(codes.WAF_ConnectorAndDescription),
},
{
"name": this.Lang(codes.WAF_ConnectorOr),
"value": firewallconfigs.HTTPFirewallRuleConnectorOr,
"description": this.Lang(codes.WAF_ConnectorOrDescription),
},
}
// 所有可选的动作
var actionMaps = []maps.Map{}
for _, action := range firewallconfigs.AllActions {
actionMaps = append(actionMaps, maps.Map{
"name": action.Name,
"description": action.Description,
"code": action.Code,
})
}
this.Data["actions"] = actionMaps
// 是否为全局
this.Data["isGlobalPolicy"] = firewallPolicy.ServerId == 0
this.Show()
}
func (this *CreateSetPopupAction) RunPost(params struct {
GroupId int64
Name string
FormType string
// normal
RulesJSON []byte
Connector string
ActionsJSON []byte
IgnoreLocal bool
IgnoreSearchEngine bool
// code
Code string
Must *actions.Must
}) {
groupConfig, err := dao.SharedHTTPFirewallRuleGroupDAO.FindRuleGroupConfig(this.AdminContext(), params.GroupId)
if err != nil {
this.ErrorPage(err)
return
}
if groupConfig == nil {
this.Fail("找不到分组Id" + strconv.FormatInt(params.GroupId, 10))
return
}
params.Must.
Field("name", params.Name).
Require("请输入规则集名称")
var setConfigJSON []byte
if params.FormType == "normal" {
if len(params.RulesJSON) == 0 {
this.Fail("请添加至少一个规则")
return
}
var rules = []*firewallconfigs.HTTPFirewallRule{}
err = json.Unmarshal(params.RulesJSON, &rules)
if err != nil {
this.ErrorPage(err)
return
}
if len(rules) == 0 {
this.Fail("请添加至少一个规则")
return
}
var actionConfigs = []*firewallconfigs.HTTPFirewallActionConfig{}
if len(params.ActionsJSON) > 0 {
err = json.Unmarshal(params.ActionsJSON, &actionConfigs)
if err != nil {
this.ErrorPage(err)
return
}
}
if len(actionConfigs) == 0 {
this.Fail("请添加至少一个动作")
return
}
var setConfig = &firewallconfigs.HTTPFirewallRuleSet{
Id: 0,
IsOn: true,
Name: params.Name,
Code: "",
Description: "",
Connector: params.Connector,
RuleRefs: nil,
Rules: rules,
Actions: actionConfigs,
IgnoreLocal: params.IgnoreLocal,
IgnoreSearchEngine: params.IgnoreSearchEngine,
}
setConfigJSON, err = json.Marshal(setConfig)
if err != nil {
this.ErrorPage(err)
return
}
} else if params.FormType == "code" {
var codeJSON = []byte(params.Code)
if len(codeJSON) == 0 {
this.FailField("code", "请输入规则集代码")
return
}
var setConfig = &firewallconfigs.HTTPFirewallRuleSet{}
err = json.Unmarshal(codeJSON, setConfig)
if err != nil {
this.FailField("code", "解析规则集代码失败:"+err.Error())
return
}
if len(setConfig.Rules) == 0 {
this.FailField("code", "规则集代码中必须包含至少一个规则")
return
}
if len(setConfig.Actions) == 0 {
this.FailField("code", "规则集代码中必须包含至少一个动作")
return
}
setConfig.Name = params.Name
setConfig.IsOn = true
// 重置ID
setConfig.Id = 0
setConfig.RuleRefs = nil
for _, rule := range setConfig.Rules {
rule.Id = 0
}
err = setConfig.Init()
if err != nil {
this.FailField("code", "校验规则集代码失败:"+err.Error())
return
}
setConfigJSON, err = json.Marshal(setConfig)
} else {
this.Fail("错误的参数'formType': " + params.FormType)
return
}
createUpdateResp, err := this.RPC().HTTPFirewallRuleSetRPC().CreateOrUpdateHTTPFirewallRuleSetFromConfig(this.AdminContext(), &pb.CreateOrUpdateHTTPFirewallRuleSetFromConfigRequest{FirewallRuleSetConfigJSON: setConfigJSON})
if err != nil {
this.ErrorPage(err)
return
}
groupConfig.SetRefs = append(groupConfig.SetRefs, &firewallconfigs.HTTPFirewallRuleSetRef{
IsOn: true,
SetId: createUpdateResp.FirewallRuleSetId,
})
setRefsJSON, err := json.Marshal(groupConfig.SetRefs)
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallRuleGroupRPC().UpdateHTTPFirewallRuleGroupSets(this.AdminContext(), &pb.UpdateHTTPFirewallRuleGroupSetsRequest{
FirewallRuleGroupId: params.GroupId,
FirewallRuleSetsJSON: setRefsJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Data["setId"] = createUpdateResp.FirewallRuleSetId
this.Success()
}

View File

@@ -0,0 +1,35 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type DeleteAction struct {
actionutils.ParentAction
}
func (this *DeleteAction) RunPost(params struct {
FirewallPolicyId int64
}) {
// 日志
defer this.CreateLogInfo(codes.WAFPolicy_LogDeleteWAFPolicy, params.FirewallPolicyId)
countResp, err := this.RPC().NodeClusterRPC().CountAllEnabledNodeClustersWithHTTPFirewallPolicyId(this.AdminContext(), &pb.CountAllEnabledNodeClustersWithHTTPFirewallPolicyIdRequest{HttpFirewallPolicyId: params.FirewallPolicyId})
if err != nil {
this.ErrorPage(err)
return
}
if countResp.Count > 0 {
this.Fail("此WAF策略正在被有些集群引用请修改后再删除。")
}
_, err = this.RPC().HTTPFirewallPolicyRPC().DeleteHTTPFirewallPolicy(this.AdminContext(), &pb.DeleteHTTPFirewallPolicyRequest{HttpFirewallPolicyId: params.FirewallPolicyId})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,56 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type DeleteGroupAction struct {
actionutils.ParentAction
}
func (this *DeleteGroupAction) RunPost(params struct {
FirewallPolicyId int64
GroupId int64
}) {
// 日志
defer this.CreateLogInfo(codes.WAFRuleGroup_LogDeleteRuleGroup, params.FirewallPolicyId, params.GroupId)
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
firewallPolicy.RemoveRuleGroup(params.GroupId)
inboundJSON, err := firewallPolicy.InboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
outboundJSON, err := firewallPolicy.OutboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallPolicyRPC().UpdateHTTPFirewallPolicyGroups(this.AdminContext(), &pb.UpdateHTTPFirewallPolicyGroupsRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
InboundJSON: inboundJSON,
OutboundJSON: outboundJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,54 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
)
type DeleteSetAction struct {
actionutils.ParentAction
}
func (this *DeleteSetAction) RunPost(params struct {
GroupId int64
SetId int64
}) {
// 日志
defer this.CreateLogInfo(codes.WAFRuleSet_LogDeleteRuleSet, params.GroupId, params.SetId)
groupConfig, err := dao.SharedHTTPFirewallRuleGroupDAO.FindRuleGroupConfig(this.AdminContext(), params.GroupId)
if err != nil {
this.ErrorPage(err)
return
}
if groupConfig == nil {
this.NotFound("firewallRuleGroup", params.GroupId)
return
}
newRefs := []*firewallconfigs.HTTPFirewallRuleSetRef{}
for _, ref := range groupConfig.SetRefs {
if ref.SetId != params.SetId {
newRefs = append(newRefs, ref)
}
}
newRefsJSON, err := json.Marshal(newRefs)
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallRuleGroupRPC().UpdateHTTPFirewallRuleGroupSets(this.AdminContext(), &pb.UpdateHTTPFirewallRuleGroupSetsRequest{
FirewallRuleGroupId: params.GroupId,
FirewallRuleSetsJSON: newRefsJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,134 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/ttlcache"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/rands"
"time"
)
type ExportAction struct {
actionutils.ParentAction
}
func (this *ExportAction) Init() {
this.Nav("", "", "export")
}
func (this *ExportAction) RunGet(params struct {
FirewallPolicyId int64
}) {
policy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if policy == nil {
this.NotFound("firewallPolicy", policy.Id)
return
}
enabledInboundGroups := []*firewallconfigs.HTTPFirewallRuleGroup{}
enabledOutboundGroups := []*firewallconfigs.HTTPFirewallRuleGroup{}
disabledInboundGroups := []*firewallconfigs.HTTPFirewallRuleGroup{}
disabledOutboundGroups := []*firewallconfigs.HTTPFirewallRuleGroup{}
if policy.Inbound != nil {
for _, g := range policy.Inbound.Groups {
if g.IsOn {
enabledInboundGroups = append(enabledInboundGroups, g)
} else {
disabledInboundGroups = append(disabledInboundGroups, g)
}
}
}
if policy.Outbound != nil {
for _, g := range policy.Outbound.Groups {
if g.IsOn {
enabledOutboundGroups = append(enabledOutboundGroups, g)
} else {
disabledOutboundGroups = append(disabledOutboundGroups, g)
}
}
}
this.Data["enabledInboundGroups"] = enabledInboundGroups
this.Data["enabledOutboundGroups"] = enabledOutboundGroups
this.Data["disabledInboundGroups"] = disabledInboundGroups
this.Data["disabledOutboundGroups"] = disabledOutboundGroups
this.Show()
}
func (this *ExportAction) RunPost(params struct {
FirewallPolicyId int64
InboundGroupIds []int64
OutboundGroupIds []int64
Must *actions.Must
CSRF *actionutils.CSRF
}) {
defer this.CreateLogInfo(codes.WAFPolicy_LogExportWAFPolicy, params.FirewallPolicyId)
policy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if policy == nil {
this.NotFound("firewallPolicy", policy.Id)
return
}
// inbound
newInboundGroups := []*firewallconfigs.HTTPFirewallRuleGroup{}
for _, inboundGroupId := range params.InboundGroupIds {
group := policy.FindRuleGroup(inboundGroupId)
if group != nil {
newInboundGroups = append(newInboundGroups, group)
}
}
if policy.Inbound == nil {
policy.Inbound = &firewallconfigs.HTTPFirewallInboundConfig{
IsOn: true,
}
}
policy.Inbound.Groups = newInboundGroups
policy.Inbound.GroupRefs = nil
// outbound
newOutboundGroups := []*firewallconfigs.HTTPFirewallRuleGroup{}
for _, outboundGroupId := range params.OutboundGroupIds {
group := policy.FindRuleGroup(outboundGroupId)
if group != nil {
newOutboundGroups = append(newOutboundGroups, group)
}
}
if policy.Outbound == nil {
policy.Outbound = &firewallconfigs.HTTPFirewallOutboundConfig{
IsOn: true,
}
}
policy.Outbound.Groups = newOutboundGroups
policy.Outbound.GroupRefs = nil
configJSON, err := json.Marshal(policy)
if err != nil {
this.ErrorPage(err)
return
}
key := "waf." + rands.HexString(32)
ttlcache.DefaultCache.Write(key, configJSON, time.Now().Unix()+600)
this.Data["key"] = key
this.Data["id"] = params.FirewallPolicyId
this.Success()
}

View File

@@ -0,0 +1,39 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/ttlcache"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/iwind/TeaGo/types"
"strconv"
)
type ExportDownloadAction struct {
actionutils.ParentAction
}
func (this *ExportDownloadAction) Init() {
this.Nav("", "", "")
}
func (this *ExportDownloadAction) RunGet(params struct {
Key string
PolicyId int64
}) {
item := ttlcache.DefaultCache.Read(params.Key)
if item == nil || item.Value == nil {
this.WriteString("找不到要导出的内容")
return
}
ttlcache.DefaultCache.Delete(params.Key)
data, ok := item.Value.([]byte)
if ok {
this.AddHeader("Content-Disposition", "attachment; filename=\"WAF-"+types.String(params.PolicyId)+".json\";")
this.AddHeader("Content-Length", strconv.Itoa(len(data)))
_, _ = this.Write(data)
} else {
this.WriteString("找不到要导出的内容")
return
}
}

View File

@@ -0,0 +1,105 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
"strings"
)
type GroupAction struct {
actionutils.ParentAction
}
func (this *GroupAction) Init() {
this.Nav("", "", this.ParamString("type"))
}
func (this *GroupAction) RunGet(params struct {
FirewallPolicyId int64
GroupId int64
Type string
}) {
this.Data["type"] = params.Type
//stime := time.Now()
// policy
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
//fmt.Printf("调用 FindEnabledHTTPFirewallPolicyConfig 方法 耗时: %v\n", time.Now().Sub(stime))
// group config
groupConfig, err := dao.SharedHTTPFirewallRuleGroupDAO.FindRuleGroupConfig(this.AdminContext(), params.GroupId)
if err != nil {
this.ErrorPage(err)
return
}
if groupConfig == nil {
this.NotFound("firewallRuleGroup", params.GroupId)
return
}
//fmt.Printf("调用 FindRuleGroupConfig 方法 耗时: %v\n", time.Now().Sub(stime))
this.Data["group"] = groupConfig
// rule sets
this.Data["sets"] = lists.Map(groupConfig.Sets, func(k int, v interface{}) interface{} {
set := v.(*firewallconfigs.HTTPFirewallRuleSet)
// 动作说明
var actionMaps = []maps.Map{}
for _, action := range set.Actions {
def := firewallconfigs.FindActionDefinition(action.Code)
if def == nil {
continue
}
actionMaps = append(actionMaps, maps.Map{
"code": strings.ToUpper(action.Code),
"name": def.Name,
"category": def.Category,
"options": action.Options,
})
}
return maps.Map{
"id": set.Id,
"name": set.Name,
"rules": lists.Map(set.Rules, func(k int, v interface{}) interface{} {
rule := v.(*firewallconfigs.HTTPFirewallRule)
// 校验
var errString = ""
var err = rule.Init()
if err != nil {
errString = err.Error()
}
return maps.Map{
"param": rule.Param,
"paramFilters": rule.ParamFilters,
"operator": rule.Operator,
"value": rule.Value,
"isCaseInsensitive": rule.IsCaseInsensitive,
"description": rule.Description,
"isComposed": firewallconfigs.CheckCheckpointIsComposed(rule.Prefix()),
"checkpointOptions": rule.CheckpointOptions,
"err": errString,
}
}),
"isOn": set.IsOn,
"actions": actionMaps,
"connector": strings.ToUpper(set.Connector),
}
})
//fmt.Printf("调用 list.map 方法 耗时: %v\n", time.Now().Sub(stime))
this.Show()
}

View File

@@ -0,0 +1,74 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/iwind/TeaGo/maps"
)
type GroupsAction struct {
actionutils.ParentAction
}
func (this *GroupsAction) Init() {
this.Nav("", "", this.ParamString("type"))
}
func (this *GroupsAction) RunGet(params struct {
FirewallPolicyId int64
Type string
}) {
this.Data["type"] = params.Type
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
groupMaps := []maps.Map{}
// inbound
if params.Type == "inbound" {
if firewallPolicy.Inbound != nil {
for _, g := range firewallPolicy.Inbound.Groups {
groupMaps = append(groupMaps, maps.Map{
"id": g.Id,
"name": g.Name,
"code": g.Code,
"isOn": g.IsOn,
"description": g.Description,
"countSets": len(g.Sets),
"isTemplate": g.IsTemplate,
"canDelete": true, //!g.IsTemplate,
})
}
}
}
// outbound
if params.Type == "outbound" {
if firewallPolicy.Outbound != nil {
for _, g := range firewallPolicy.Outbound.Groups {
groupMaps = append(groupMaps, maps.Map{
"id": g.Id,
"name": g.Name,
"code": g.Code,
"isOn": g.IsOn,
"description": g.Description,
"countSets": len(g.Sets),
"isTemplate": g.IsTemplate,
"canDelete": true, //!g.IsTemplate,
})
}
}
}
this.Data["groups"] = groupMaps
this.Show()
}

View File

@@ -0,0 +1,71 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
"net/http"
)
type Helper struct {
}
func NewHelper() *Helper {
return &Helper{}
}
func (this *Helper) BeforeAction(actionPtr actions.ActionWrapper) (goNext bool) {
action := actionPtr.Object()
if action.Request.Method != http.MethodGet {
return true
}
action.Data["mainTab"] = "component"
action.Data["secondMenuItem"] = "waf"
// 显示当前的防火墙名称
firewallPolicyId := action.ParamInt64("firewallPolicyId")
if firewallPolicyId > 0 {
action.Data["firewallPolicyId"] = firewallPolicyId
action.Data["countInboundGroups"] = 0
action.Data["countOutboundGroups"] = 0
parentAction := actionutils.FindParentAction(actionPtr)
if parentAction != nil {
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicy(parentAction.AdminContext(), firewallPolicyId)
if err != nil {
parentAction.ErrorPage(err)
return
}
if firewallPolicy == nil {
action.WriteString("can not find firewall policy")
return
}
action.Data["firewallPolicyName"] = firewallPolicy.Name
// inbound
if len(firewallPolicy.InboundJSON) > 0 {
inboundConfig := &firewallconfigs.HTTPFirewallInboundConfig{}
err = json.Unmarshal(firewallPolicy.InboundJSON, inboundConfig)
if err != nil {
parentAction.ErrorPage(err)
return
}
action.Data["countInboundGroups"] = len(inboundConfig.GroupRefs)
}
// outbound
if len(firewallPolicy.OutboundJSON) > 0 {
outboundConfig := &firewallconfigs.HTTPFirewallOutboundConfig{}
err = json.Unmarshal(firewallPolicy.OutboundJSON, outboundConfig)
if err != nil {
parentAction.ErrorPage(err)
return
}
action.Data["countOutboundGroups"] = len(outboundConfig.GroupRefs)
}
}
}
return true
}

View File

@@ -0,0 +1,326 @@
package waf
import (
"bytes"
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/utils/exce"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/actions"
stringutil "github.com/iwind/TeaGo/utils/string"
"os"
)
type ImportAction struct {
actionutils.ParentAction
}
func (this *ImportAction) Init() {
this.Nav("", "", "import")
}
func (this *ImportAction) RunGet(params struct{}) {
this.Show()
}
func (this *ImportAction) RunPost(params struct {
FirewallPolicyId int64
File *actions.File
Must *actions.Must
CSRF *actionutils.CSRF
}) {
defer this.CreateLogInfo(codes.WAFPolicy_LogImportWAFPolicy, params.FirewallPolicyId)
if params.File == nil {
this.Fail("请上传要导入的文件")
}
if params.File.Ext != ".json" {
this.Fail("规则文件的扩展名只能是.json")
}
data, err := params.File.Read()
if err != nil {
this.Fail("读取文件时发生错误:" + err.Error())
}
config := &firewallconfigs.HTTPFirewallPolicy{}
err = json.Unmarshal(data, config)
if err != nil {
this.Fail("解析文件时发生错误:" + err.Error())
}
_, err = this.RPC().HTTPFirewallPolicyRPC().ImportHTTPFirewallPolicy(this.AdminContext(), &pb.ImportHTTPFirewallPolicyRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
HttpFirewallPolicyJSON: data,
})
if err != nil {
this.Fail("导入失败:" + err.Error())
}
this.Success()
}
func (this *ImportAction) importXlsxWAFRules(data []byte, firewallPolicyId int64) {
// 解析文件
errRulesBuff, rules, err := exce.ParseRules(bytes.NewReader(data))
if err != nil {
this.Fail("导入失败:" + err.Error())
}
groupSetMaps := map[int64]map[string]int64{}
inboundGroupNameMaps := map[string]int64{}
outboundGroupNameMaps := map[string]int64{}
newInboundGroup := []int64{}
newOutboundGroup := []int64{}
// 批量加入waf规则
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), firewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", firewallPolicyId)
}
for _, g := range firewallPolicy.Inbound.GroupRefs {
// 查询group 下的规则集
group, err := dao.SharedHTTPFirewallRuleGroupDAO.FindRuleGroupConfig(this.AdminContext(), g.GroupId)
if err != nil {
this.Fail("获取策略下规则分组信息失败:" + err.Error())
}
inboundGroupNameMaps[group.Name] = group.Id
groupSetMaps[g.GroupId] = make(map[string]int64, len(group.Sets))
for _, set := range group.Sets {
groupSetMaps[g.GroupId][set.Name] = set.Id
}
}
for _, g := range firewallPolicy.Outbound.GroupRefs {
// 查询group 下的规则集
group, err := dao.SharedHTTPFirewallRuleGroupDAO.FindRuleGroupConfig(this.AdminContext(), g.GroupId)
if err != nil {
this.Fail("获取策略下规则分组信息失败:" + err.Error())
}
outboundGroupNameMaps[group.Name] = group.Id
groupSetMaps[g.GroupId] = make(map[string]int64, len(group.Sets))
for _, set := range group.Sets {
groupSetMaps[g.GroupId][set.Name] = set.Id
}
}
for _, rule := range rules {
var inboundGroupId int64
var outboundGroupId int64
var ok bool
if rule.Inbound {
inboundGroupId, ok = inboundGroupNameMaps[rule.Type]
if !ok { // 如果不存在 则创建新的入站规则分组
createResp, err := this.RPC().HTTPFirewallRuleGroupRPC().CreateHTTPFirewallRuleGroup(this.AdminContext(), &pb.CreateHTTPFirewallRuleGroupRequest{
IsOn: true,
Name: rule.Type,
Code: rule.Type,
Description: "WAF规则导入" + rule.Type,
})
if err != nil {
this.ErrorPage(err)
return
}
inboundGroupId = createResp.FirewallRuleGroupId
newInboundGroup = append(newInboundGroup, inboundGroupId)
inboundGroupNameMaps[rule.Type] = inboundGroupId
}
}
if rule.Outbound {
outboundGroupId, ok = outboundGroupNameMaps[rule.Type]
if !ok { // 如果不存在 则创建新的入站规则分组
createResp, err := this.RPC().HTTPFirewallRuleGroupRPC().CreateHTTPFirewallRuleGroup(this.AdminContext(), &pb.CreateHTTPFirewallRuleGroupRequest{
IsOn: true,
Name: rule.Type,
Code: rule.Type,
Description: "WAF规则导入" + rule.Type,
})
if err != nil {
this.ErrorPage(err)
return
}
outboundGroupId = createResp.FirewallRuleGroupId
newOutboundGroup = append(newOutboundGroup, outboundGroupId)
outboundGroupNameMaps[rule.Type] = outboundGroupId
}
}
// 往规则分组中加入新规则集
var rs = []*firewallconfigs.HTTPFirewallRule{} //入站规则
var outRs = make([]*firewallconfigs.HTTPFirewallRule, 1) // 出站规则
for idx, arg := range rule.Position {
if arg == "" {
continue
}
if arg == "${responseBody}" { // 出站规则
outRs[0] = &firewallconfigs.HTTPFirewallRule{
Id: 0,
IsOn: true,
Param: "{responseBody}",
Operator: "match",
Value: rule.Regular,
IsCaseInsensitive: true,
IsComposed: false,
}
} else {
// 入站规则才支持多规则
if rule.IsAnd {
rs = append(rs, &firewallconfigs.HTTPFirewallRule{
Id: 0,
IsOn: true,
Param: arg,
Operator: "match",
Value: rule.Regulars[idx],
IsCaseInsensitive: true,
IsComposed: false,
})
} else {
rs = append(rs, &firewallconfigs.HTTPFirewallRule{
Id: 0,
IsOn: true,
Param: arg,
Operator: "match",
Value: rule.Regular,
IsCaseInsensitive: true,
IsComposed: false,
})
}
}
}
var set = &firewallconfigs.HTTPFirewallRuleSet{
Id: 0,
IsOn: true,
Name: rule.Name,
Code: "",
Description: rule.Description,
Connector: "or",
RuleRefs: nil,
Level: rule.Level,
CVE: rule.CVE,
// 默认动作为403显示网页
Actions: []*firewallconfigs.HTTPFirewallActionConfig{
{
Code: firewallconfigs.HTTPFirewallActionPage,
Options: map[string]interface{}{
"useDefault": true,
"status": 403,
"body": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t<title>403 Forbidden</title>\n\t<style>\n\t\taddress { line-height: 1.8; }\n\t</style>\n</head>\n<body>\n<h1>403 Forbidden</h1>\n<address>Connection: ${remoteAddr} (Client) -&gt; ${serverAddr} (Server)</address>\n<address>Request ID: ${requestId}</address>\n</body>\n</html>",
},
},
},
IgnoreLocal: false,
}
if rule.IsAnd {
set.Connector = "and"
}
// 判断规则集中是否存在相同的规则集名字 如果有替换
// 如果是已存在的分组则判断
if rule.Inbound {
if ok {
set.Id, ok = groupSetMaps[inboundGroupId][set.Name]
}
set.Rules = rs
setConfigJSON, err := json.Marshal(set)
if err != nil {
this.ErrorPage(err)
return
}
if ok { // 替换
_, err = this.RPC().HTTPFirewallRuleSetRPC().CreateOrUpdateHTTPFirewallRuleSetFromConfig(this.AdminContext(), &pb.CreateOrUpdateHTTPFirewallRuleSetFromConfigRequest{
FirewallRuleSetConfigJSON: setConfigJSON,
})
} else {
_, err = this.RPC().HTTPFirewallRuleGroupRPC().AddHTTPFirewallRuleGroupSet(this.AdminContext(), &pb.AddHTTPFirewallRuleGroupSetRequest{
FirewallRuleGroupId: inboundGroupId,
FirewallRuleSetConfigJSON: setConfigJSON,
})
}
if err != nil {
this.ErrorPage(err)
return
}
}
if rule.Outbound {
if ok {
set.Id, ok = groupSetMaps[outboundGroupId][set.Name]
}
set.Rules = outRs
setConfigJSON, err := json.Marshal(set)
if err != nil {
this.ErrorPage(err)
return
}
if ok { // 替换
_, err = this.RPC().HTTPFirewallRuleSetRPC().CreateOrUpdateHTTPFirewallRuleSetFromConfig(this.AdminContext(), &pb.CreateOrUpdateHTTPFirewallRuleSetFromConfigRequest{
FirewallRuleSetConfigJSON: setConfigJSON,
})
} else {
_, err = this.RPC().HTTPFirewallRuleGroupRPC().AddHTTPFirewallRuleGroupSet(this.AdminContext(), &pb.AddHTTPFirewallRuleGroupSetRequest{
FirewallRuleGroupId: outboundGroupId,
FirewallRuleSetConfigJSON: setConfigJSON,
})
}
if err != nil {
this.ErrorPage(err)
return
}
}
}
// 修改策略 当前的入站规则分组
for _, groupId := range newInboundGroup {
firewallPolicy.Inbound.GroupRefs = append(firewallPolicy.Inbound.GroupRefs, &firewallconfigs.HTTPFirewallRuleGroupRef{
IsOn: true,
GroupId: groupId,
})
}
// 修改策略 当前的出站规则分组
for _, groupId := range newOutboundGroup {
firewallPolicy.Outbound.GroupRefs = append(firewallPolicy.Outbound.GroupRefs, &firewallconfigs.HTTPFirewallRuleGroupRef{
IsOn: true,
GroupId: groupId,
})
}
inboundJSON, err := firewallPolicy.InboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
outboundJSON, err := firewallPolicy.OutboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallPolicyRPC().UpdateHTTPFirewallPolicyGroups(this.AdminContext(), &pb.UpdateHTTPFirewallPolicyGroupsRequest{
HttpFirewallPolicyId: firewallPolicyId,
InboundJSON: inboundJSON,
OutboundJSON: outboundJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
if errRulesBuff != nil { // 导入规则中存在无法分析的规则,将其统计并返回给客户
md := stringutil.Md5(errRulesBuff.String())
_ = os.MkdirAll(Tea.TmpDir(), 0755)
_ = os.WriteFile(Tea.TmpFile(md+".xlsx"), errRulesBuff.Bytes(), 0755)
//this.AddHeader("Content-Disposition", "attachment; filename=\"WAF-ALL-Error.xlsx\";")
//this.AddHeader("Content-Length", strconv.Itoa(errRulesBuff.Len()))
//this.AddHeader("Content-Type", "application/vnd.ms-excel; charset=utf-8")
//this.AddHeader("Content-Transfer-Encoding", "binary")
//_, _ = this.Write(errRulesBuff.Bytes())
this.Data["key"] = md
}
this.Success()
}

View File

@@ -0,0 +1,48 @@
/*
@Author: dp
@Description:
@File: importErr
@Version: 1.0.0
@Date: 2025-03-24 17:23
*/
/*
@Author: 1usir
@Description:
@File: importErr.go
@Version: 1.0.0
@Date: 2024/2/28 14:58
*/
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/iwind/TeaGo/Tea"
"os"
"strconv"
)
type ImportErrAction struct {
actionutils.ParentAction
}
func (this *ImportErrAction) Init() {
this.Nav("", "", "")
}
func (this *ImportErrAction) RunGet(params struct {
Key string
}) {
filename := Tea.TmpFile(params.Key + ".xlsx")
fs, err := os.ReadFile(filename)
if err != nil {
this.WriteString("找不到要导出的内容")
return
}
this.AddHeader("Content-Disposition", "attachment; filename=\"WAF-ALL-Error.xlsx\";")
this.AddHeader("Content-Length", strconv.Itoa(len(fs)))
this.AddHeader("Content-Type", "application/vnd.ms-excel; charset=utf-8")
this.AddHeader("Content-Transfer-Encoding", "binary")
_, _ = this.Write(fs)
_ = os.RemoveAll(filename)
}

View File

@@ -0,0 +1,99 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/maps"
)
type IndexAction struct {
actionutils.ParentAction
}
func (this *IndexAction) Init() {
this.FirstMenu("index")
}
func (this *IndexAction) RunGet(params struct {
Keyword string
ClusterId int64
}) {
this.Data["keyword"] = params.Keyword
this.Data["clusterId"] = params.ClusterId
countResp, err := this.RPC().HTTPFirewallPolicyRPC().CountAllEnabledHTTPFirewallPolicies(this.AdminContext(), &pb.CountAllEnabledHTTPFirewallPoliciesRequest{
NodeClusterId: params.ClusterId,
Keyword: params.Keyword,
})
if err != nil {
this.ErrorPage(err)
return
}
var count = countResp.Count
var page = this.NewPage(count)
listResp, err := this.RPC().HTTPFirewallPolicyRPC().ListEnabledHTTPFirewallPolicies(this.AdminContext(), &pb.ListEnabledHTTPFirewallPoliciesRequest{
NodeClusterId: params.ClusterId,
Keyword: params.Keyword,
Offset: page.Offset,
Size: page.Size,
})
if err != nil {
this.ErrorPage(err)
return
}
var policyMaps = []maps.Map{}
for _, policy := range listResp.HttpFirewallPolicies {
var countInbound = 0
var countOutbound = 0
if len(policy.InboundJSON) > 0 {
inboundConfig := &firewallconfigs.HTTPFirewallInboundConfig{}
err = json.Unmarshal(policy.InboundJSON, inboundConfig)
if err != nil {
this.ErrorPage(err)
return
}
countInbound = len(inboundConfig.GroupRefs)
}
if len(policy.OutboundJSON) > 0 {
outboundConfig := &firewallconfigs.HTTPFirewallInboundConfig{}
err = json.Unmarshal(policy.OutboundJSON, outboundConfig)
if err != nil {
this.ErrorPage(err)
return
}
countOutbound = len(outboundConfig.GroupRefs)
}
countClustersResp, err := this.RPC().NodeClusterRPC().CountAllEnabledNodeClustersWithHTTPFirewallPolicyId(this.AdminContext(), &pb.CountAllEnabledNodeClustersWithHTTPFirewallPolicyIdRequest{HttpFirewallPolicyId: policy.Id})
if err != nil {
this.ErrorPage(err)
return
}
var countClusters = countClustersResp.Count
// mode
if len(policy.Mode) == 0 {
policy.Mode = firewallconfigs.FirewallModeDefend
}
policyMaps = append(policyMaps, maps.Map{
"id": policy.Id,
"isOn": policy.IsOn,
"name": policy.Name,
"mode": policy.Mode,
"modeInfo": firewallconfigs.FindFirewallMode(policy.Mode),
"countInbound": countInbound,
"countOutbound": countOutbound,
"countClusters": countClusters,
})
}
this.Data["policies"] = policyMaps
this.Data["page"] = page.AsHTML()
this.Show()
}

View File

@@ -0,0 +1,57 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/configloaders"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/waf/ipadmin"
"github.com/TeaOSLab/EdgeAdmin/internal/web/helpers"
"github.com/iwind/TeaGo"
)
func init() {
TeaGo.BeforeStart(func(server *TeaGo.Server) {
server.
Helper(helpers.NewUserMustAuth(configloaders.AdminModuleCodeServer)).
Helper(NewHelper()).
Data("teaMenu", "servers").
Data("teaSubMenu", "waf").
Prefix("/servers/components/waf").
Get("", new(IndexAction)).
GetPost("/createPopup", new(CreatePopupAction)).
Post("/delete", new(DeleteAction)).
Get("/policy", new(PolicyAction)).
Post("/upgradeTemplate", new(UpgradeTemplateAction)).
Get("/groups", new(GroupsAction)).
Get("/group", new(GroupAction)).
Get("/log", new(LogAction)).
GetPost("/update", new(UpdateAction)).
GetPost("/test", new(TestAction)).
GetPost("/export", new(ExportAction)).
Get("/exportDownload", new(ExportDownloadAction)).
GetPost("/import", new(ImportAction)).
Get("/importErr", new(ImportErrAction)).
Post("/updateGroupOn", new(UpdateGroupOnAction)).
Post("/deleteGroup", new(DeleteGroupAction)).
GetPost("/createGroupPopup", new(CreateGroupPopupAction)).
Post("/sortGroups", new(SortGroupsAction)).
GetPost("/updateGroupPopup", new(UpdateGroupPopupAction)).
GetPost("/createSetPopup", new(CreateSetPopupAction)).
GetPost("/createRulePopup", new(CreateRulePopupAction)).
Post("/sortSets", new(SortSetsAction)).
Post("/updateSetOn", new(UpdateSetOnAction)).
Post("/deleteSet", new(DeleteSetAction)).
GetPost("/updateSetPopup", new(UpdateSetPopupAction)).
Get("/setCodePopup", new(SetCodePopupAction)).
Post("/count", new(CountAction)).
Get("/selectPopup", new(SelectPopupAction)).
Post("/testRegexp", new(TestRegexpAction)).
// IP管理
GetPost("/ipadmin", new(ipadmin.IndexAction)).
GetPost("/ipadmin/provinces", new(ipadmin.ProvincesAction)).
Get("/ipadmin/lists", new(ipadmin.ListsAction)).
GetPost("/ipadmin/updateIPPopup", new(ipadmin.UpdateIPPopupAction)).
Post("/ipadmin/deleteIP", new(ipadmin.DeleteIPAction)).
GetPost("/ipadmin/test", new(ipadmin.TestAction)).
EndAll()
})
}

View File

@@ -0,0 +1,29 @@
package ipadmin
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type DeleteIPAction struct {
actionutils.ParentAction
}
func (this *DeleteIPAction) RunPost(params struct {
FirewallPolicyId int64
ItemId int64
}) {
// 日志
defer this.CreateLogInfo(codes.WAF_LogDeleteIPFromWAFPolicy, params.FirewallPolicyId, params.ItemId)
// TODO 判断权限
_, err := this.RPC().IPItemRPC().DeleteIPItem(this.AdminContext(), &pb.DeleteIPItemRequest{IpItemId: params.ItemId})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,175 @@
package ipadmin
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
"strings"
)
type IndexAction struct {
actionutils.ParentAction
}
func (this *IndexAction) Init() {
this.Nav("", "", "ipadmin")
}
func (this *IndexAction) RunGet(params struct {
FirewallPolicyId int64
}) {
this.Data["subMenuItem"] = "region"
// 当前选中的地区
policyConfig, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if policyConfig == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
var deniedCountryIds = []int64{}
var allowedCountryIds = []int64{}
var countryHTML string
var allowSearchEngine bool
if policyConfig.Inbound != nil && policyConfig.Inbound.Region != nil {
deniedCountryIds = policyConfig.Inbound.Region.DenyCountryIds
allowedCountryIds = policyConfig.Inbound.Region.AllowCountryIds
countryHTML = policyConfig.Inbound.Region.CountryHTML
allowSearchEngine = policyConfig.Inbound.Region.AllowSearchEngine
}
this.Data["countryHTML"] = countryHTML
this.Data["allowSearchEngine"] = allowSearchEngine
countriesResp, err := this.RPC().RegionCountryRPC().FindAllRegionCountries(this.AdminContext(), &pb.FindAllRegionCountriesRequest{})
if err != nil {
this.ErrorPage(err)
return
}
var deniesCountryMaps = []maps.Map{}
var allowedCountryMaps = []maps.Map{}
for _, country := range countriesResp.RegionCountries {
var countryMap = maps.Map{
"id": country.Id,
"name": country.DisplayName,
"letter": strings.ToUpper(string(country.Pinyin[0][0])),
}
if lists.ContainsInt64(deniedCountryIds, country.Id) {
deniesCountryMaps = append(deniesCountryMaps, countryMap)
}
if lists.ContainsInt64(allowedCountryIds, country.Id) {
allowedCountryMaps = append(allowedCountryMaps, countryMap)
}
}
this.Data["deniedCountries"] = deniesCountryMaps
this.Data["allowedCountries"] = allowedCountryMaps
// except & only URL Patterns
this.Data["exceptURLPatterns"] = []*shared.URLPattern{}
this.Data["onlyURLPatterns"] = []*shared.URLPattern{}
if policyConfig.Inbound != nil && policyConfig.Inbound.Region != nil {
if len(policyConfig.Inbound.Region.CountryExceptURLPatterns) > 0 {
this.Data["exceptURLPatterns"] = policyConfig.Inbound.Region.CountryExceptURLPatterns
}
if len(policyConfig.Inbound.Region.CountryOnlyURLPatterns) > 0 {
this.Data["onlyURLPatterns"] = policyConfig.Inbound.Region.CountryOnlyURLPatterns
}
}
this.Show()
}
func (this *IndexAction) RunPost(params struct {
FirewallPolicyId int64
DenyCountryIds []int64
AllowCountryIds []int64
ExceptURLPatternsJSON []byte
OnlyURLPatternsJSON []byte
CountryHTML string
AllowSearchEngine bool
Must *actions.Must
}) {
// 日志
defer this.CreateLogInfo(codes.WAF_LogUpdateForbiddenCountries, params.FirewallPolicyId)
policyConfig, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if policyConfig == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
if policyConfig.Inbound == nil {
policyConfig.Inbound = &firewallconfigs.HTTPFirewallInboundConfig{IsOn: true}
}
if policyConfig.Inbound.Region == nil {
policyConfig.Inbound.Region = &firewallconfigs.HTTPFirewallRegionConfig{
IsOn: true,
}
}
policyConfig.Inbound.Region.DenyCountryIds = params.DenyCountryIds
policyConfig.Inbound.Region.AllowCountryIds = params.AllowCountryIds
// 例外URL
var exceptURLPatterns = []*shared.URLPattern{}
if len(params.ExceptURLPatternsJSON) > 0 {
err = json.Unmarshal(params.ExceptURLPatternsJSON, &exceptURLPatterns)
if err != nil {
this.Fail("校验例外URL参数失败" + err.Error())
return
}
}
policyConfig.Inbound.Region.CountryExceptURLPatterns = exceptURLPatterns
// 自定义提示
if len(params.CountryHTML) > 32<<10 {
this.Fail("提示内容长度不能超出32K")
return
}
policyConfig.Inbound.Region.CountryHTML = params.CountryHTML
policyConfig.Inbound.Region.AllowSearchEngine = params.AllowSearchEngine
// 限制URL
var onlyURLPatterns = []*shared.URLPattern{}
if len(params.OnlyURLPatternsJSON) > 0 {
err = json.Unmarshal(params.OnlyURLPatternsJSON, &onlyURLPatterns)
if err != nil {
this.Fail("校验限制URL参数失败" + err.Error())
return
}
}
policyConfig.Inbound.Region.CountryOnlyURLPatterns = onlyURLPatterns
inboundJSON, err := json.Marshal(policyConfig.Inbound)
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallPolicyRPC().UpdateHTTPFirewallInboundConfig(this.AdminContext(), &pb.UpdateHTTPFirewallInboundConfigRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
InboundJSON: inboundJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,120 @@
package ipadmin
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/maps"
timeutil "github.com/iwind/TeaGo/utils/time"
"time"
)
type ListsAction struct {
actionutils.ParentAction
}
func (this *ListsAction) Init() {
this.Nav("", "", "ipadmin")
}
func (this *ListsAction) RunGet(params struct {
FirewallPolicyId int64
Type string
}) {
this.Data["subMenuItem"] = params.Type
this.Data["type"] = params.Type
listId, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledPolicyIPListIdWithType(this.AdminContext(), params.FirewallPolicyId, params.Type)
if err != nil {
this.ErrorPage(err)
return
}
this.Data["listId"] = listId
// 数量
countResp, err := this.RPC().IPItemRPC().CountIPItemsWithListId(this.AdminContext(), &pb.CountIPItemsWithListIdRequest{IpListId: listId})
if err != nil {
this.ErrorPage(err)
return
}
var count = countResp.Count
var page = this.NewPage(count)
this.Data["page"] = page.AsHTML()
// 列表
itemsResp, err := this.RPC().IPItemRPC().ListIPItemsWithListId(this.AdminContext(), &pb.ListIPItemsWithListIdRequest{
IpListId: listId,
Offset: page.Offset,
Size: page.Size,
})
if err != nil {
this.ErrorPage(err)
return
}
var itemMaps = []maps.Map{}
for _, item := range itemsResp.IpItems {
var expiredTime = ""
if item.ExpiredAt > 0 {
expiredTime = timeutil.FormatTime("Y-m-d H:i:s", item.ExpiredAt)
}
// policy
var sourcePolicyMap = maps.Map{"id": 0}
if item.SourceHTTPFirewallPolicy != nil {
sourcePolicyMap = maps.Map{
"id": item.SourceHTTPFirewallPolicy.Id,
"name": item.SourceHTTPFirewallPolicy.Name,
"serverId": item.SourceHTTPFirewallPolicy.ServerId,
}
}
// group
var sourceGroupMap = maps.Map{"id": 0}
if item.SourceHTTPFirewallRuleGroup != nil {
sourceGroupMap = maps.Map{
"id": item.SourceHTTPFirewallRuleGroup.Id,
"name": item.SourceHTTPFirewallRuleGroup.Name,
}
}
// set
var sourceSetMap = maps.Map{"id": 0}
if item.SourceHTTPFirewallRuleSet != nil {
sourceSetMap = maps.Map{
"id": item.SourceHTTPFirewallRuleSet.Id,
"name": item.SourceHTTPFirewallRuleSet.Name,
}
}
// server
var sourceServerMap = maps.Map{"id": 0}
if item.SourceServer != nil {
sourceServerMap = maps.Map{
"id": item.SourceServer.Id,
"name": item.SourceServer.Name,
}
}
itemMaps = append(itemMaps, maps.Map{
"id": item.Id,
"value": item.Value,
"ipFrom": item.IpFrom,
"ipTo": item.IpTo,
"createdTime": timeutil.FormatTime("Y-m-d", item.CreatedAt),
"expiredTime": expiredTime,
"reason": item.Reason,
"type": item.Type,
"eventLevelName": firewallconfigs.FindFirewallEventLevelName(item.EventLevel),
"sourcePolicy": sourcePolicyMap,
"sourceGroup": sourceGroupMap,
"sourceSet": sourceSetMap,
"sourceServer": sourceServerMap,
"lifeSeconds": item.ExpiredAt - time.Now().Unix(),
})
}
this.Data["items"] = itemMaps
this.Show()
}

View File

@@ -0,0 +1,171 @@
package ipadmin
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/regionconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
)
type ProvincesAction struct {
actionutils.ParentAction
}
func (this *ProvincesAction) Init() {
this.Nav("", "", "ipadmin")
}
func (this *ProvincesAction) RunGet(params struct {
FirewallPolicyId int64
}) {
this.Data["subMenuItem"] = "province"
// 当前选中的省份
policyConfig, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if policyConfig == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
var deniedProvinceIds = []int64{}
var allowedProvinceIds = []int64{}
var provinceHTML string
if policyConfig.Inbound != nil && policyConfig.Inbound.Region != nil {
deniedProvinceIds = policyConfig.Inbound.Region.DenyProvinceIds
allowedProvinceIds = policyConfig.Inbound.Region.AllowProvinceIds
provinceHTML = policyConfig.Inbound.Region.ProvinceHTML
}
this.Data["provinceHTML"] = provinceHTML
provincesResp, err := this.RPC().RegionProvinceRPC().FindAllRegionProvincesWithRegionCountryId(this.AdminContext(), &pb.FindAllRegionProvincesWithRegionCountryIdRequest{
RegionCountryId: regionconfigs.RegionChinaId,
})
if err != nil {
this.ErrorPage(err)
return
}
var deniedProvinceMaps = []maps.Map{}
var allowedProvinceMaps = []maps.Map{}
for _, province := range provincesResp.RegionProvinces {
var provinceMap = maps.Map{
"id": province.Id,
"name": province.DisplayName,
}
if lists.ContainsInt64(deniedProvinceIds, province.Id) {
deniedProvinceMaps = append(deniedProvinceMaps, provinceMap)
}
if lists.ContainsInt64(allowedProvinceIds, province.Id) {
allowedProvinceMaps = append(allowedProvinceMaps, provinceMap)
}
}
this.Data["deniedProvinces"] = deniedProvinceMaps
this.Data["allowedProvinces"] = allowedProvinceMaps
// except & only URL Patterns
this.Data["exceptURLPatterns"] = []*shared.URLPattern{}
this.Data["onlyURLPatterns"] = []*shared.URLPattern{}
if policyConfig.Inbound != nil && policyConfig.Inbound.Region != nil {
if len(policyConfig.Inbound.Region.ProvinceExceptURLPatterns) > 0 {
this.Data["exceptURLPatterns"] = policyConfig.Inbound.Region.ProvinceExceptURLPatterns
}
if len(policyConfig.Inbound.Region.ProvinceOnlyURLPatterns) > 0 {
this.Data["onlyURLPatterns"] = policyConfig.Inbound.Region.ProvinceOnlyURLPatterns
}
}
this.Show()
}
func (this *ProvincesAction) RunPost(params struct {
FirewallPolicyId int64
DenyProvinceIds []int64
AllowProvinceIds []int64
ExceptURLPatternsJSON []byte
OnlyURLPatternsJSON []byte
ProvinceHTML string
Must *actions.Must
}) {
// 日志
defer this.CreateLogInfo(codes.WAF_LogUpdateForbiddenProvinces, params.FirewallPolicyId)
policyConfig, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if policyConfig == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
if policyConfig.Inbound == nil {
policyConfig.Inbound = &firewallconfigs.HTTPFirewallInboundConfig{IsOn: true}
}
if policyConfig.Inbound.Region == nil {
policyConfig.Inbound.Region = &firewallconfigs.HTTPFirewallRegionConfig{
IsOn: true,
}
}
policyConfig.Inbound.Region.DenyProvinceIds = params.DenyProvinceIds
policyConfig.Inbound.Region.AllowProvinceIds = params.AllowProvinceIds
// 例外URL
var exceptURLPatterns = []*shared.URLPattern{}
if len(params.ExceptURLPatternsJSON) > 0 {
err = json.Unmarshal(params.ExceptURLPatternsJSON, &exceptURLPatterns)
if err != nil {
this.Fail("校验例外URL参数失败" + err.Error())
return
}
}
policyConfig.Inbound.Region.ProvinceExceptURLPatterns = exceptURLPatterns
// 限制URL
var onlyURLPatterns = []*shared.URLPattern{}
if len(params.OnlyURLPatternsJSON) > 0 {
err = json.Unmarshal(params.OnlyURLPatternsJSON, &onlyURLPatterns)
if err != nil {
this.Fail("校验限制URL参数失败" + err.Error())
return
}
}
policyConfig.Inbound.Region.ProvinceOnlyURLPatterns = onlyURLPatterns
// 自定义提示
if len(params.ProvinceHTML) > 32<<10 {
this.Fail("提示内容长度不能超出32K")
return
}
policyConfig.Inbound.Region.ProvinceHTML = params.ProvinceHTML
inboundJSON, err := json.Marshal(policyConfig.Inbound)
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallPolicyRPC().UpdateHTTPFirewallInboundConfig(this.AdminContext(), &pb.UpdateHTTPFirewallInboundConfigRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
InboundJSON: inboundJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,90 @@
package ipadmin
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
timeutil "github.com/iwind/TeaGo/utils/time"
)
type TestAction struct {
actionutils.ParentAction
}
func (this *TestAction) Init() {
this.Nav("", "", "ipadmin")
}
func (this *TestAction) RunGet(params struct {
FirewallPolicyId int64
}) {
this.Data["subMenuItem"] = "test"
this.Show()
}
func (this *TestAction) RunPost(params struct {
FirewallPolicyId int64
Ip string
Must *actions.Must
}) {
resp, err := this.RPC().HTTPFirewallPolicyRPC().CheckHTTPFirewallPolicyIPStatus(this.AdminContext(), &pb.CheckHTTPFirewallPolicyIPStatusRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
Ip: params.Ip,
})
if err != nil {
this.ErrorPage(err)
return
}
resultMap := maps.Map{
"isDone": true,
"isFound": resp.IsFound,
"isOk": resp.IsOk,
"error": resp.Error,
"isAllowed": resp.IsAllowed,
}
if resp.IpList != nil {
resultMap["list"] = maps.Map{
"id": resp.IpList.Id,
"name": resp.IpList.Name,
}
}
if resp.IpItem != nil {
resultMap["item"] = maps.Map{
"id": resp.IpItem.Id,
"value": resp.IpItem.Value,
"ipFrom": resp.IpItem.IpFrom,
"ipTo": resp.IpItem.IpTo,
"reason": resp.IpItem.Reason,
"createdTime": timeutil.FormatTime("Y-m-d", resp.IpItem.CreatedAt),
"expiredAt": resp.IpItem.ExpiredAt,
"expiredTime": timeutil.FormatTime("Y-m-d H:i:s", resp.IpItem.ExpiredAt),
"type": resp.IpItem.Type,
"eventLevelName": firewallconfigs.FindFirewallEventLevelName(resp.IpItem.EventLevel),
"listType": resp.IpItem.ListType,
}
}
if resp.RegionCountry != nil {
resultMap["country"] = maps.Map{
"id": resp.RegionCountry.Id,
"name": resp.RegionCountry.Name,
}
}
if resp.RegionProvince != nil {
resultMap["province"] = maps.Map{
"id": resp.RegionProvince.Id,
"name": resp.RegionProvince.Name,
}
}
this.Data["result"] = resultMap
this.Success()
}

View File

@@ -0,0 +1,96 @@
package ipadmin
import (
"github.com/TeaOSLab/EdgeAdmin/internal/utils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
)
type UpdateIPPopupAction struct {
actionutils.ParentAction
}
func (this *UpdateIPPopupAction) Init() {
this.Nav("", "", "")
}
func (this *UpdateIPPopupAction) RunGet(params struct {
ItemId int64
}) {
itemResp, err := this.RPC().IPItemRPC().FindEnabledIPItem(this.AdminContext(), &pb.FindEnabledIPItemRequest{IpItemId: params.ItemId})
if err != nil {
this.ErrorPage(err)
return
}
item := itemResp.IpItem
if item == nil {
this.NotFound("ipItem", params.ItemId)
return
}
this.Data["item"] = maps.Map{
"id": item.Id,
"value": item.Value,
"ipFrom": item.IpFrom,
"ipTo": item.IpTo,
"expiredAt": item.ExpiredAt,
"reason": item.Reason,
"type": item.Type,
"eventLevel": item.EventLevel,
}
this.Data["type"] = item.Type
this.Show()
}
func (this *UpdateIPPopupAction) RunPost(params struct {
FirewallPolicyId int64
ItemId int64
Value string
ExpiredAt int64
Reason string
Type string
EventLevel string
Must *actions.Must
CSRF *actionutils.CSRF
}) {
// 日志
defer this.CreateLogInfo(codes.WAF_LogUpdateIPFromWAFPolicy, params.FirewallPolicyId, params.ItemId)
switch params.Type {
case "ip":
// 校验IP格式
params.Must.
Field("value", params.Value).
Require("请输入IP或IP段")
_, _, _, ok := utils.ParseIPValue(params.Value)
if !ok {
this.FailField("value", "请输入正确的IP格式")
return
}
case "all":
params.Value = "0.0.0.0"
}
_, err := this.RPC().IPItemRPC().UpdateIPItem(this.AdminContext(), &pb.UpdateIPItemRequest{
IpItemId: params.ItemId,
Value: params.Value,
ExpiredAt: params.ExpiredAt,
Reason: params.Reason,
Type: params.Type,
EventLevel: params.EventLevel,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,222 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/iplibrary"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
timeutil "github.com/iwind/TeaGo/utils/time"
"regexp"
"strings"
)
type LogAction struct {
actionutils.ParentAction
}
func (this *LogAction) Init() {
this.Nav("", "", "log")
}
func (this *LogAction) RunGet(params struct {
Day string
RequestId string
FirewallPolicyId int64
GroupId int64
Partition int32 `default:"-1"`
}) {
if len(params.Day) == 0 {
params.Day = timeutil.Format("Y-m-d")
}
this.Data["path"] = this.Request.URL.Path
this.Data["day"] = params.Day
this.Data["groupId"] = params.GroupId
this.Data["accessLogs"] = []maps.Map{}
this.Data["partition"] = params.Partition
var day = params.Day
var ipList = []string{}
var wafMaps = []maps.Map{}
if len(day) > 0 && regexp.MustCompile(`\d{4}-\d{2}-\d{2}`).MatchString(day) {
day = strings.ReplaceAll(day, "-", "")
var size = int64(20)
resp, err := this.RPC().HTTPAccessLogRPC().ListHTTPAccessLogs(this.AdminContext(), &pb.ListHTTPAccessLogsRequest{
Partition: params.Partition,
RequestId: params.RequestId,
FirewallPolicyId: params.FirewallPolicyId,
FirewallRuleGroupId: params.GroupId,
Day: day,
Size: size,
})
if err != nil {
this.ErrorPage(err)
return
}
if len(resp.HttpAccessLogs) == 0 {
this.Data["accessLogs"] = []interface{}{}
} else {
this.Data["accessLogs"] = resp.HttpAccessLogs
for _, accessLog := range resp.HttpAccessLogs {
// IP
if len(accessLog.RemoteAddr) > 0 {
if !lists.ContainsString(ipList, accessLog.RemoteAddr) {
ipList = append(ipList, accessLog.RemoteAddr)
}
}
// WAF信息集合
if accessLog.FirewallPolicyId > 0 && accessLog.FirewallRuleGroupId > 0 && accessLog.FirewallRuleSetId > 0 {
// 检查Set是否已经存在
var existSet = false
for _, wafMap := range wafMaps {
if wafMap.GetInt64("setId") == accessLog.FirewallRuleSetId {
existSet = true
break
}
}
if !existSet {
wafMaps = append(wafMaps, maps.Map{
"policyId": accessLog.FirewallPolicyId,
"groupId": accessLog.FirewallRuleGroupId,
"setId": accessLog.FirewallRuleSetId,
})
}
}
}
}
this.Data["hasMore"] = resp.HasMore
this.Data["nextRequestId"] = resp.RequestId
// 上一个requestId
this.Data["hasPrev"] = false
this.Data["lastRequestId"] = ""
if len(params.RequestId) > 0 {
this.Data["hasPrev"] = true
prevResp, err := this.RPC().HTTPAccessLogRPC().ListHTTPAccessLogs(this.AdminContext(), &pb.ListHTTPAccessLogsRequest{
Partition: params.Partition,
RequestId: params.RequestId,
FirewallPolicyId: params.FirewallPolicyId,
FirewallRuleGroupId: params.GroupId,
Day: day,
Size: size,
Reverse: true,
})
if err != nil {
this.ErrorPage(err)
return
}
if int64(len(prevResp.HttpAccessLogs)) == size {
this.Data["lastRequestId"] = prevResp.RequestId
}
}
}
// 所有分组
policyResp, err := this.RPC().HTTPFirewallPolicyRPC().FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), &pb.FindEnabledHTTPFirewallPolicyConfigRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
})
if err != nil {
this.ErrorPage(err)
return
}
policyConfig := &firewallconfigs.HTTPFirewallPolicy{}
err = json.Unmarshal(policyResp.HttpFirewallPolicyJSON, policyConfig)
if err != nil {
this.ErrorPage(err)
return
}
groupMaps := []maps.Map{}
for _, group := range policyConfig.AllRuleGroups() {
groupMaps = append(groupMaps, maps.Map{
"id": group.Id,
"name": group.Name,
})
}
this.Data["groups"] = groupMaps
// 根据IP查询区域
this.Data["regions"] = iplibrary.LookupIPSummaries(ipList)
// WAF相关
var wafInfos = map[int64]maps.Map{} // set id => WAF Map
var wafPolicyCacheMap = map[int64]*pb.HTTPFirewallPolicy{} // id => *pb.HTTPFirewallPolicy
var wafGroupCacheMap = map[int64]*pb.HTTPFirewallRuleGroup{} // id => *pb.HTTPFirewallRuleGroup
var wafSetCacheMap = map[int64]*pb.HTTPFirewallRuleSet{} // id => *pb.HTTPFirewallRuleSet
for _, wafMap := range wafMaps {
var policyId = wafMap.GetInt64("policyId")
var groupId = wafMap.GetInt64("groupId")
var setId = wafMap.GetInt64("setId")
if policyId > 0 {
pbPolicy, ok := wafPolicyCacheMap[policyId]
if !ok {
policyResp, err := this.RPC().HTTPFirewallPolicyRPC().FindEnabledHTTPFirewallPolicy(this.AdminContext(), &pb.FindEnabledHTTPFirewallPolicyRequest{HttpFirewallPolicyId: policyId})
if err != nil {
this.ErrorPage(err)
return
}
pbPolicy = policyResp.HttpFirewallPolicy
wafPolicyCacheMap[policyId] = pbPolicy
}
if pbPolicy != nil {
wafMap = maps.Map{
"policy": maps.Map{
"id": pbPolicy.Id,
"name": pbPolicy.Name,
"serverId": pbPolicy.ServerId,
},
}
if groupId > 0 {
pbGroup, ok := wafGroupCacheMap[groupId]
if !ok {
groupResp, err := this.RPC().HTTPFirewallRuleGroupRPC().FindEnabledHTTPFirewallRuleGroup(this.AdminContext(), &pb.FindEnabledHTTPFirewallRuleGroupRequest{FirewallRuleGroupId: groupId})
if err != nil {
this.ErrorPage(err)
return
}
pbGroup = groupResp.FirewallRuleGroup
wafGroupCacheMap[groupId] = pbGroup
}
if pbGroup != nil {
wafMap["group"] = maps.Map{
"id": pbGroup.Id,
"name": pbGroup.Name,
}
if setId > 0 {
pbSet, ok := wafSetCacheMap[setId]
if !ok {
setResp, err := this.RPC().HTTPFirewallRuleSetRPC().FindEnabledHTTPFirewallRuleSet(this.AdminContext(), &pb.FindEnabledHTTPFirewallRuleSetRequest{FirewallRuleSetId: setId})
if err != nil {
this.ErrorPage(err)
return
}
pbSet = setResp.FirewallRuleSet
wafSetCacheMap[setId] = pbSet
}
if pbSet != nil {
wafMap["set"] = maps.Map{
"id": pbSet.Id,
"name": pbSet.Name,
}
}
}
}
}
}
}
wafInfos[setId] = wafMap
}
this.Data["wafInfos"] = wafInfos
this.Show()
}

View File

@@ -0,0 +1,126 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/utils/numberutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/maps"
)
type PolicyAction struct {
actionutils.ParentAction
}
func (this *PolicyAction) Init() {
this.Nav("", "", "index")
}
func (this *PolicyAction) RunGet(params struct {
FirewallPolicyId int64
}) {
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
var internalGroups = []maps.Map{}
if firewallPolicy.Inbound != nil {
for _, group := range firewallPolicy.Inbound.Groups {
internalGroups = append(internalGroups, maps.Map{
"name": group.Name,
"isOn": group.IsOn,
})
}
}
if firewallPolicy.Outbound != nil {
for _, group := range firewallPolicy.Outbound.Groups {
internalGroups = append(internalGroups, maps.Map{
"name": group.Name,
"isOn": group.IsOn,
})
}
}
// 检查是否有升级
var templatePolicy = firewallconfigs.HTTPFirewallTemplate()
var upgradeItems = []maps.Map{}
if templatePolicy.Inbound != nil {
for _, group := range templatePolicy.Inbound.Groups {
if len(group.Code) == 0 {
continue
}
var oldGroup = firewallPolicy.FindRuleGroupWithCode(group.Code)
if oldGroup == nil {
upgradeItems = append(upgradeItems, maps.Map{
"name": group.Name,
"isOn": group.IsOn,
})
continue
}
for _, set := range group.Sets {
if len(set.Code) == 0 {
continue
}
var oldSet = oldGroup.FindRuleSetWithCode(set.Code)
if oldSet == nil {
upgradeItems = append(upgradeItems, maps.Map{
"name": group.Name + " -- " + set.Name,
"isOn": set.IsOn,
})
continue
}
}
}
}
this.Data["upgradeItems"] = upgradeItems
// 模式
if len(firewallPolicy.Mode) == 0 {
firewallPolicy.Mode = firewallconfigs.FirewallModeDefend
}
this.Data["firewallPolicy"] = maps.Map{
"id": firewallPolicy.Id,
"name": firewallPolicy.Name,
"isOn": firewallPolicy.IsOn,
"description": firewallPolicy.Description,
"mode": firewallPolicy.Mode,
"modeInfo": firewallconfigs.FindFirewallMode(firewallPolicy.Mode),
"groups": internalGroups,
"blockOptions": firewallPolicy.BlockOptions,
"pageOptions": firewallPolicy.PageOptions,
"captchaOptions": firewallPolicy.CaptchaOptions,
"jsCookieOptions": firewallPolicy.JSCookieOptions,
"useLocalFirewall": firewallPolicy.UseLocalFirewall,
"synFlood": firewallPolicy.SYNFlood,
"log": firewallPolicy.Log,
"maxRequestBodySize": firewallPolicy.MaxRequestBodySize,
"maxRequestBodySizeFormat": numberutils.FormatBytes(firewallPolicy.MaxRequestBodySize),
"denyCountryHTML": firewallPolicy.DenyCountryHTML,
"denyProvinceHTML": firewallPolicy.DenyProvinceHTML,
}
// 正在使用此策略的集群
clustersResp, err := this.RPC().NodeClusterRPC().FindAllEnabledNodeClustersWithHTTPFirewallPolicyId(this.AdminContext(), &pb.FindAllEnabledNodeClustersWithHTTPFirewallPolicyIdRequest{HttpFirewallPolicyId: params.FirewallPolicyId})
if err != nil {
this.ErrorPage(err)
return
}
clusterMaps := []maps.Map{}
for _, cluster := range clustersResp.NodeClusters {
clusterMaps = append(clusterMaps, maps.Map{
"id": cluster.Id,
"name": cluster.Name,
})
}
this.Data["clusters"] = clusterMaps
this.Show()
}

View File

@@ -0,0 +1,73 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/maps"
)
type SelectPopupAction struct {
actionutils.ParentAction
}
func (this *SelectPopupAction) Init() {
this.FirstMenu("index")
}
func (this *SelectPopupAction) RunGet(params struct{}) {
countResp, err := this.RPC().HTTPFirewallPolicyRPC().CountAllEnabledHTTPFirewallPolicies(this.AdminContext(), &pb.CountAllEnabledHTTPFirewallPoliciesRequest{})
if err != nil {
this.ErrorPage(err)
return
}
count := countResp.Count
page := this.NewPage(count)
listResp, err := this.RPC().HTTPFirewallPolicyRPC().ListEnabledHTTPFirewallPolicies(this.AdminContext(), &pb.ListEnabledHTTPFirewallPoliciesRequest{
Offset: page.Offset,
Size: page.Size,
})
if err != nil {
this.ErrorPage(err)
return
}
policyMaps := []maps.Map{}
for _, policy := range listResp.HttpFirewallPolicies {
countInbound := 0
countOutbound := 0
if len(policy.InboundJSON) > 0 {
inboundConfig := &firewallconfigs.HTTPFirewallInboundConfig{}
err = json.Unmarshal(policy.InboundJSON, inboundConfig)
if err != nil {
this.ErrorPage(err)
return
}
countInbound = len(inboundConfig.GroupRefs)
}
if len(policy.OutboundJSON) > 0 {
outboundConfig := &firewallconfigs.HTTPFirewallInboundConfig{}
err = json.Unmarshal(policy.OutboundJSON, outboundConfig)
if err != nil {
this.ErrorPage(err)
return
}
countOutbound = len(outboundConfig.GroupRefs)
}
policyMaps = append(policyMaps, maps.Map{
"id": policy.Id,
"isOn": policy.IsOn,
"name": policy.Name,
"countInbound": countInbound,
"countOutbound": countOutbound,
})
}
this.Data["policies"] = policyMaps
this.Data["page"] = page.AsHTML()
this.Show()
}

View File

@@ -0,0 +1,57 @@
// Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
)
type SetCodePopupAction struct {
actionutils.ParentAction
}
func (this *SetCodePopupAction) Init() {
this.Nav("", "", "")
}
func (this *SetCodePopupAction) RunGet(params struct {
SetId int64
}) {
setResp, err := this.RPC().HTTPFirewallRuleSetRPC().FindEnabledHTTPFirewallRuleSetConfig(this.AdminContext(), &pb.FindEnabledHTTPFirewallRuleSetConfigRequest{FirewallRuleSetId: params.SetId})
if err != nil {
this.ErrorPage(err)
return
}
if len(setResp.FirewallRuleSetJSON) == 0 {
this.NotFound("httpFirewallRuleSet", params.SetId)
return
}
var ruleSet = &firewallconfigs.HTTPFirewallRuleSet{}
err = json.Unmarshal(setResp.FirewallRuleSetJSON, ruleSet)
if err != nil {
this.ErrorPage(err)
return
}
ruleSet.RuleRefs = nil
ruleSet.Id = 0
for _, rule := range ruleSet.Rules {
rule.Id = 0
}
this.Data["setName"] = ruleSet.Name
codeJSON, err := json.MarshalIndent(ruleSet, "", " ")
if err != nil {
this.ErrorPage(err)
return
}
this.Data["code"] = string(codeJSON)
this.Show()
}

View File

@@ -0,0 +1,86 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
)
type SortGroupsAction struct {
actionutils.ParentAction
}
func (this *SortGroupsAction) RunPost(params struct {
FirewallPolicyId int64
Type string
GroupIds []int64
}) {
// 日志
defer this.CreateLogInfo(codes.WAFRuleGroup_LogSortRuleGroups, params.FirewallPolicyId)
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
switch params.Type {
case "inbound":
refMapping := map[int64]*firewallconfigs.HTTPFirewallRuleGroupRef{}
for _, ref := range firewallPolicy.Inbound.GroupRefs {
refMapping[ref.GroupId] = ref
}
newRefs := []*firewallconfigs.HTTPFirewallRuleGroupRef{}
for _, groupId := range params.GroupIds {
ref, ok := refMapping[groupId]
if ok {
newRefs = append(newRefs, ref)
}
}
firewallPolicy.Inbound.GroupRefs = newRefs
case "outbound":
refMapping := map[int64]*firewallconfigs.HTTPFirewallRuleGroupRef{}
for _, ref := range firewallPolicy.Outbound.GroupRefs {
refMapping[ref.GroupId] = ref
}
newRefs := []*firewallconfigs.HTTPFirewallRuleGroupRef{}
for _, groupId := range params.GroupIds {
ref, ok := refMapping[groupId]
if ok {
newRefs = append(newRefs, ref)
}
}
firewallPolicy.Outbound.GroupRefs = newRefs
}
inboundJSON, err := firewallPolicy.InboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
outboundJSON, err := firewallPolicy.OutboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallPolicyRPC().UpdateHTTPFirewallPolicyGroups(this.AdminContext(), &pb.UpdateHTTPFirewallPolicyGroupsRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
InboundJSON: inboundJSON,
OutboundJSON: outboundJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,61 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
)
type SortSetsAction struct {
actionutils.ParentAction
}
func (this *SortSetsAction) RunPost(params struct {
GroupId int64
SetIds []int64
}) {
// 日志
defer this.CreateLogInfo(codes.WAFRuleSet_LogSortRuleSets, params.GroupId)
groupConfig, err := dao.SharedHTTPFirewallRuleGroupDAO.FindRuleGroupConfig(this.AdminContext(), params.GroupId)
if err != nil {
this.ErrorPage(err)
return
}
if groupConfig == nil {
this.NotFound("firewallRuleGroup", params.GroupId)
return
}
setMap := map[int64]*firewallconfigs.HTTPFirewallRuleSetRef{}
for _, setRef := range groupConfig.SetRefs {
setMap[setRef.SetId] = setRef
}
newRefs := []*firewallconfigs.HTTPFirewallRuleSetRef{}
for _, setId := range params.SetIds {
ref, ok := setMap[setId]
if ok {
newRefs = append(newRefs, ref)
}
}
newRefsJSON, err := json.Marshal(newRefs)
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallRuleGroupRPC().UpdateHTTPFirewallRuleGroupSets(this.AdminContext(), &pb.UpdateHTTPFirewallRuleGroupSetsRequest{
FirewallRuleGroupId: params.GroupId,
FirewallRuleSetsJSON: newRefsJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,15 @@
package waf
import "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
type TestAction struct {
actionutils.ParentAction
}
func (this *TestAction) Init() {
this.Nav("", "", "test")
}
func (this *TestAction) RunGet(params struct{}) {
this.Show()
}

View File

@@ -0,0 +1,48 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/iwind/TeaGo/maps"
"regexp"
"strings"
)
type TestRegexpAction struct {
actionutils.ParentAction
}
func (this *TestRegexpAction) RunPost(params struct {
Regexp string
IsCaseInsensitive bool
Body string
}) {
var exp = params.Regexp
if params.IsCaseInsensitive && !strings.HasPrefix(params.Regexp, "(?i)") {
exp = "(?i)" + exp
}
reg, err := regexp.Compile(exp)
if err != nil {
this.Data["result"] = maps.Map{
"isOk": false,
"message": "解析正则出错:" + err.Error(),
}
this.Success()
}
if reg.MatchString(params.Body) {
this.Data["result"] = maps.Map{
"isOk": true,
"message": "匹配成功",
}
this.Success()
}
this.Data["result"] = maps.Map{
"isOk": false,
"message": "匹配失败",
}
this.Success()
}

View File

@@ -0,0 +1,223 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
)
type UpdateAction struct {
actionutils.ParentAction
}
func (this *UpdateAction) Init() {
this.Nav("", "", "update")
}
func (this *UpdateAction) RunGet(params struct {
FirewallPolicyId int64
}) {
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
// block options
if firewallPolicy.BlockOptions == nil {
firewallPolicy.BlockOptions = firewallconfigs.NewHTTPFirewallBlockAction()
}
// page options
if firewallPolicy.PageOptions == nil {
firewallPolicy.PageOptions = firewallconfigs.NewHTTPFirewallPageAction()
}
// jscookie options
if firewallPolicy.JSCookieOptions == nil {
firewallPolicy.JSCookieOptions = firewallconfigs.NewHTTPFirewallJavascriptCookieAction()
}
// mode
if len(firewallPolicy.Mode) == 0 {
firewallPolicy.Mode = firewallconfigs.FirewallModeDefend
}
this.Data["modes"] = firewallconfigs.FindAllFirewallModes()
// syn flood
if firewallPolicy.SYNFlood == nil {
firewallPolicy.SYNFlood = &firewallconfigs.SYNFloodConfig{
IsOn: false,
MinAttempts: 10,
TimeoutSeconds: 600,
IgnoreLocal: true,
}
}
// log
if firewallPolicy.Log == nil {
firewallPolicy.Log = firewallconfigs.DefaultHTTPFirewallPolicyLogConfig
}
this.Data["firewallPolicy"] = maps.Map{
"id": firewallPolicy.Id,
"name": firewallPolicy.Name,
"description": firewallPolicy.Description,
"isOn": firewallPolicy.IsOn,
"mode": firewallPolicy.Mode,
"blockOptions": firewallPolicy.BlockOptions,
"pageOptions": firewallPolicy.PageOptions,
"captchaOptions": firewallPolicy.CaptchaOptions,
"jsCookieOptions": firewallPolicy.JSCookieOptions,
"useLocalFirewall": firewallPolicy.UseLocalFirewall,
"synFloodConfig": firewallPolicy.SYNFlood,
"log": firewallPolicy.Log,
"maxRequestBodySize": types.String(firewallPolicy.MaxRequestBodySize),
"denyCountryHTML": firewallPolicy.DenyCountryHTML,
"denyProvinceHTML": firewallPolicy.DenyProvinceHTML,
}
// 预置分组
var groups = []maps.Map{}
templatePolicy := firewallconfigs.HTTPFirewallTemplate()
for _, group := range templatePolicy.AllRuleGroups() {
if len(group.Code) > 0 {
usedGroup := firewallPolicy.FindRuleGroupWithCode(group.Code)
if usedGroup != nil {
group.IsOn = usedGroup.IsOn
}
}
groups = append(groups, maps.Map{
"code": group.Code,
"name": group.Name,
"isOn": group.IsOn,
})
}
this.Data["groups"] = groups
this.Show()
}
func (this *UpdateAction) RunPost(params struct {
FirewallPolicyId int64
Name string
GroupCodes []string
BlockOptionsJSON []byte
PageOptionsJSON []byte
CaptchaOptionsJSON []byte
JsCookieOptionsJSON []byte
Description string
IsOn bool
Mode string
UseLocalFirewall bool
SynFloodJSON []byte
LogJSON []byte
MaxRequestBodySize int64
DenyCountryHTML string
DenyProvinceHTML string
Must *actions.Must
}) {
// 日志
defer this.CreateLogInfo(codes.WAFPolicy_LogUpdateWAFPolicy, params.FirewallPolicyId)
params.Must.
Field("name", params.Name).
Require("请输入策略名称")
// 校验拦截选项JSON
var blockOptions = firewallconfigs.NewHTTPFirewallBlockAction()
err := json.Unmarshal(params.BlockOptionsJSON, blockOptions)
if err != nil {
this.Fail("拦截动作参数校验失败:" + err.Error())
return
}
// 校验显示页面选项JSON
var pageOptions = firewallconfigs.NewHTTPFirewallPageAction()
err = json.Unmarshal(params.PageOptionsJSON, pageOptions)
if err != nil {
this.Fail("校验显示页面动作配置失败:" + err.Error())
return
}
if pageOptions.Status < 100 && pageOptions.Status > 999 {
this.Fail("显示页面动作的状态码配置错误:" + types.String(pageOptions.Status))
return
}
// 校验验证码选项JSON
var captchaOptions = firewallconfigs.NewHTTPFirewallCaptchaAction()
err = json.Unmarshal(params.CaptchaOptionsJSON, captchaOptions)
if err != nil {
this.Fail("验证码动作参数校验失败:" + err.Error())
return
}
// 检查极验配置
if captchaOptions.CaptchaType == firewallconfigs.CaptchaTypeGeeTest || captchaOptions.GeeTestConfig.IsOn {
if captchaOptions.CaptchaType == firewallconfigs.CaptchaTypeGeeTest && !captchaOptions.GeeTestConfig.IsOn {
this.Fail("人机识别动作配置的默认验证方式为极验-行为验,所以需要选择允许用户使用极验")
return
}
if len(captchaOptions.GeeTestConfig.CaptchaId) == 0 {
this.FailField("geetestCaptchaId", "请输入极验-验证ID")
return
}
if len(captchaOptions.GeeTestConfig.CaptchaKey) == 0 {
this.FailField("geetestCaptchaKey", "请输入极验-验证Key")
return
}
}
// 校验JSCookie选项JSON
var jsCookieOptions = firewallconfigs.NewHTTPFirewallJavascriptCookieAction()
if len(params.JsCookieOptionsJSON) > 0 {
err = json.Unmarshal(params.JsCookieOptionsJSON, jsCookieOptions)
if err != nil {
this.Fail("JSCookie动作参数校验失败" + err.Error())
return
}
}
// 最大内容尺寸
if params.MaxRequestBodySize < 0 {
params.MaxRequestBodySize = 0
}
_, err = this.RPC().HTTPFirewallPolicyRPC().UpdateHTTPFirewallPolicy(this.AdminContext(), &pb.UpdateHTTPFirewallPolicyRequest{
HttpFirewallPolicyId: params.FirewallPolicyId,
IsOn: params.IsOn,
Name: params.Name,
Description: params.Description,
FirewallGroupCodes: params.GroupCodes,
BlockOptionsJSON: params.BlockOptionsJSON,
PageOptionsJSON: params.PageOptionsJSON,
CaptchaOptionsJSON: params.CaptchaOptionsJSON,
JsCookieOptionsJSON: params.JsCookieOptionsJSON,
Mode: params.Mode,
UseLocalFirewall: params.UseLocalFirewall,
SynFloodJSON: params.SynFloodJSON,
LogJSON: params.LogJSON,
MaxRequestBodySize: params.MaxRequestBodySize,
DenyCountryHTML: params.DenyCountryHTML,
DenyProvinceHTML: params.DenyProvinceHTML,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,30 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type UpdateGroupOnAction struct {
actionutils.ParentAction
}
func (this *UpdateGroupOnAction) RunPost(params struct {
GroupId int64
IsOn bool
}) {
// 日志
defer this.CreateLogInfo(codes.WAFRuleGroup_LogUpdateRuleGroupIsOn, params.GroupId)
_, err := this.RPC().HTTPFirewallRuleGroupRPC().UpdateHTTPFirewallRuleGroupIsOn(this.AdminContext(), &pb.UpdateHTTPFirewallRuleGroupIsOnRequest{
FirewallRuleGroupId: params.GroupId,
IsOn: params.IsOn,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,73 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
)
type UpdateGroupPopupAction struct {
actionutils.ParentAction
}
func (this *UpdateGroupPopupAction) Init() {
this.Nav("", "", "")
}
func (this *UpdateGroupPopupAction) RunGet(params struct {
GroupId int64
}) {
groupConfig, err := dao.SharedHTTPFirewallRuleGroupDAO.FindRuleGroupConfig(this.AdminContext(), params.GroupId)
if err != nil {
this.ErrorPage(err)
return
}
if groupConfig == nil {
this.NotFound("ruleGroup", params.GroupId)
return
}
this.Data["group"] = maps.Map{
"id": groupConfig.Id,
"name": groupConfig.Name,
"description": groupConfig.Description,
"isOn": groupConfig.IsOn,
"code": groupConfig.Code,
}
this.Show()
}
func (this *UpdateGroupPopupAction) RunPost(params struct {
GroupId int64
Name string
Code string
Description string
IsOn bool
Must *actions.Must
}) {
// 日志
defer this.CreateLogInfo(codes.WAFRuleGroup_LogUpdateRuleGroup, params.GroupId)
params.Must.
Field("name", params.Name).
Require("请输入分组名称")
_, err := this.RPC().HTTPFirewallRuleGroupRPC().UpdateHTTPFirewallRuleGroup(this.AdminContext(), &pb.UpdateHTTPFirewallRuleGroupRequest{
FirewallRuleGroupId: params.GroupId,
IsOn: params.IsOn,
Name: params.Name,
Code: params.Code,
Description: params.Description,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,30 @@
package waf
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type UpdateSetOnAction struct {
actionutils.ParentAction
}
func (this *UpdateSetOnAction) RunPost(params struct {
SetId int64
IsOn bool
}) {
// 日志
defer this.CreateLogInfo(codes.WAFRuleSet_LogUpdateRuleSetIsOn, params.SetId)
_, err := this.RPC().HTTPFirewallRuleSetRPC().UpdateHTTPFirewallRuleSetIsOn(this.AdminContext(), &pb.UpdateHTTPFirewallRuleSetIsOnRequest{
FirewallRuleSetId: params.SetId,
IsOn: params.IsOn,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,168 @@
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps"
)
type UpdateSetPopupAction struct {
actionutils.ParentAction
}
func (this *UpdateSetPopupAction) Init() {
this.Nav("", "", "")
}
func (this *UpdateSetPopupAction) RunGet(params struct {
FirewallPolicyId int64
GroupId int64
Type string
SetId int64
}) {
// 日志
defer this.CreateLogInfo(codes.WAFRuleSet_LogUpdateRuleSet, params.SetId)
this.Data["groupId"] = params.GroupId
this.Data["type"] = params.Type
firewallPolicy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.FirewallPolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if firewallPolicy == nil {
this.NotFound("firewallPolicy", params.FirewallPolicyId)
return
}
this.Data["firewallPolicy"] = firewallPolicy
// 一些配置
this.Data["connectors"] = []maps.Map{
{
"name": this.Lang(codes.WAF_ConnectorAnd),
"value": firewallconfigs.HTTPFirewallRuleConnectorAnd,
"description": this.Lang(codes.WAF_ConnectorAndDescription),
},
{
"name": this.Lang(codes.WAF_ConnectorOr),
"value": firewallconfigs.HTTPFirewallRuleConnectorOr,
"description": this.Lang(codes.WAF_ConnectorOrDescription),
},
}
var actionMaps = []maps.Map{}
for _, action := range firewallconfigs.AllActions {
actionMaps = append(actionMaps, maps.Map{
"name": action.Name,
"description": action.Description,
"code": action.Code,
})
}
this.Data["actions"] = actionMaps
// 规则集信息
setConfig, err := dao.SharedHTTPFirewallRuleSetDAO.FindRuleSetConfig(this.AdminContext(), params.SetId)
if err != nil {
this.ErrorPage(err)
return
}
if setConfig == nil {
this.NotFound("firewallRuleSet", params.SetId)
return
}
this.Data["setConfig"] = setConfig
// action configs
actionConfigs, err := dao.SharedHTTPFirewallPolicyDAO.FindHTTPFirewallActionConfigs(this.AdminContext(), setConfig.Actions)
if err != nil {
this.ErrorPage(err)
return
}
this.Data["actionConfigs"] = actionConfigs
this.Show()
}
func (this *UpdateSetPopupAction) RunPost(params struct {
GroupId int64
SetId int64
Name string
RulesJSON []byte
Connector string
ActionsJSON []byte
IgnoreLocal bool
IgnoreSearchEngine bool
Must *actions.Must
}) {
// 规则集信息
setConfig, err := dao.SharedHTTPFirewallRuleSetDAO.FindRuleSetConfig(this.AdminContext(), params.SetId)
if err != nil {
this.ErrorPage(err)
return
}
if setConfig == nil {
this.NotFound("firewallRuleSet", params.SetId)
return
}
params.Must.
Field("name", params.Name).
Require("请输入规则集名称")
if len(params.RulesJSON) == 0 {
this.Fail("请添加至少一个规则")
return
}
var rules = []*firewallconfigs.HTTPFirewallRule{}
err = json.Unmarshal(params.RulesJSON, &rules)
if err != nil {
this.ErrorPage(err)
return
}
if len(rules) == 0 {
this.Fail("请添加至少一个规则")
return
}
var actionConfigs = []*firewallconfigs.HTTPFirewallActionConfig{}
if len(params.ActionsJSON) > 0 {
err = json.Unmarshal(params.ActionsJSON, &actionConfigs)
if err != nil {
this.ErrorPage(err)
return
}
}
if len(actionConfigs) == 0 {
this.Fail("请添加至少一个动作")
return
}
setConfig.Name = params.Name
setConfig.Connector = params.Connector
setConfig.Rules = rules
setConfig.Actions = actionConfigs
setConfig.IgnoreLocal = params.IgnoreLocal
setConfig.IgnoreSearchEngine = params.IgnoreSearchEngine
setConfigJSON, err := json.Marshal(setConfig)
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallRuleSetRPC().CreateOrUpdateHTTPFirewallRuleSetFromConfig(this.AdminContext(), &pb.CreateOrUpdateHTTPFirewallRuleSetFromConfigRequest{FirewallRuleSetConfigJSON: setConfigJSON})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}

View File

@@ -0,0 +1,125 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package waf
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
)
type UpgradeTemplateAction struct {
actionutils.ParentAction
}
func (this *UpgradeTemplateAction) RunPost(params struct {
PolicyId int64
}) {
defer this.CreateLogInfo(codes.WAFPolicy_LogUpgradeWAFPolicy, params.PolicyId)
policy, err := dao.SharedHTTPFirewallPolicyDAO.FindEnabledHTTPFirewallPolicyConfig(this.AdminContext(), params.PolicyId)
if err != nil {
this.ErrorPage(err)
return
}
if policy == nil {
this.NotFound("firewallPolicy", params.PolicyId)
return
}
// 检查是否有升级
var templatePolicy = firewallconfigs.HTTPFirewallTemplate()
if templatePolicy.Inbound != nil {
for _, group := range templatePolicy.Inbound.Groups {
if len(group.Code) == 0 {
continue
}
var oldGroup = policy.FindRuleGroupWithCode(group.Code)
if oldGroup == nil {
createGroupResp, err := this.RPC().HTTPFirewallRuleGroupRPC().CreateHTTPFirewallRuleGroup(this.AdminContext(), &pb.CreateHTTPFirewallRuleGroupRequest{
IsOn: true,
Name: group.Name,
Code: group.Code,
Description: group.Description,
})
if err != nil {
this.ErrorPage(err)
return
}
var groupId = createGroupResp.FirewallRuleGroupId
policy.Inbound.GroupRefs = append(policy.Inbound.GroupRefs, &firewallconfigs.HTTPFirewallRuleGroupRef{
IsOn: true,
GroupId: groupId,
})
for _, set := range group.Sets {
setJSON, err := json.Marshal(set)
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallRuleGroupRPC().AddHTTPFirewallRuleGroupSet(this.AdminContext(), &pb.AddHTTPFirewallRuleGroupSetRequest{
FirewallRuleGroupId: groupId,
FirewallRuleSetConfigJSON: setJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
}
continue
}
for _, set := range group.Sets {
if len(set.Code) == 0 {
continue
}
var oldSet = oldGroup.FindRuleSetWithCode(set.Code)
if oldSet == nil {
setJSON, err := json.Marshal(set)
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallRuleGroupRPC().AddHTTPFirewallRuleGroupSet(this.AdminContext(), &pb.AddHTTPFirewallRuleGroupSetRequest{
FirewallRuleGroupId: oldGroup.Id,
FirewallRuleSetConfigJSON: setJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
continue
}
}
}
}
// 保存inbound
inboundJSON, err := policy.InboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
outboundJSON, err := policy.OutboundJSON()
if err != nil {
this.ErrorPage(err)
return
}
_, err = this.RPC().HTTPFirewallPolicyRPC().UpdateHTTPFirewallPolicyGroups(this.AdminContext(), &pb.UpdateHTTPFirewallPolicyGroupsRequest{
HttpFirewallPolicyId: params.PolicyId,
InboundJSON: inboundJSON,
OutboundJSON: outboundJSON,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Success()
}