Compare commits

...

5 Commits

Author SHA1 Message Date
ryan 2220e45989 [优化] 更新 Docker 部署命令,增加对 HTTP3的支持 2026-06-02 16:49:15 +08:00
ryan 6158a487cf [优化] 添加多语言支持的验证页面文本 2026-06-02 16:11:46 +08:00
ryan 9f9c609809 [优化] 添加 HTTP/3 支持配置选项 2026-06-02 16:07:44 +08:00
ryan e4c6ce9062 [优化] 添加自定义状态码匹配方法 2026-06-02 08:34:03 +08:00
ryan 81dd44c8fc [优化] 添加自定义状态码匹配方法 2026-06-02 08:31:39 +08:00
21 changed files with 247 additions and 51 deletions
+1 -1
View File
@@ -112,7 +112,7 @@ Docker 部署可直接运行 Agent 镜像:
docker pull ghcr.io/rain-kl/openflare-agent:latest
docker rm -f openflare-agent 2>/dev/null || true
docker run -d --name openflare-agent --restart unless-stopped \
-p 80:80 -p 443:443 \
-p 80:80 -p 443:443/tcp -p 443:443/udp \
-e OPENFLARE_SERVER_URL=http://your-server:3000 \
-e OPENFLARE_AGENT_TOKEN=YOUR_AGENT_TOKEN \
ghcr.io/rain-kl/openflare-agent:latest
+1 -1
View File
@@ -102,7 +102,7 @@ Docker 部署时直接运行内置 OpenResty 的 Agent 镜像:
docker pull ghcr.io/rain-kl/openflare-agent:latest
docker rm -f openflare-agent 2>/dev/null || true
docker run -d --name openflare-agent --restart unless-stopped \
-p 80:80 -p 443:443 \
-p 80:80 -p 443:443/tcp -p 443:443/udp \
-e OPENFLARE_SERVER_URL=http://your-server:3000 \
-e OPENFLARE_AGENT_TOKEN=YOUR_AGENT_TOKEN \
ghcr.io/rain-kl/openflare-agent:latest
+2 -2
View File
@@ -168,7 +168,7 @@ Docker 部署是 Agent 推荐的部署方式。Docker 部署时直接运行 Agen
docker pull ghcr.io/rain-kl/openflare-agent:latest
docker rm -f openflare-agent 2>/dev/null || true
docker run -d --name openflare-agent --restart unless-stopped \
-p 80:80 -p 443:443 \
-p 80:80 -p 443:443/tcp -p 443:443/udp \
-v openflare-agent-data:/data \
-v ./agent.json:/etc/openflare/agent.json:ro \
ghcr.io/rain-kl/openflare-agent:latest
@@ -180,7 +180,7 @@ docker run -d --name openflare-agent --restart unless-stopped \
docker pull ghcr.io/rain-kl/openflare-agent:latest
docker rm -f openflare-agent 2>/dev/null || true
docker run -d --name openflare-agent --restart unless-stopped \
-p 80:80 -p 443:443 \
-p 80:80 -p 443:443/tcp -p 443:443/udp \
-e OPENFLARE_SERVER_URL=http://your-server:3000 \
-e OPENFLARE_AGENT_TOKEN=YOUR_AGENT_TOKEN \
ghcr.io/rain-kl/openflare-agent:latest
+1 -1
View File
@@ -119,7 +119,7 @@ Agent 部署方式推荐使用 Docker 部署(即直接运行内置 OpenResty
docker pull ghcr.io/rain-kl/openflare-agent:latest
docker rm -f openflare-agent 2>/dev/null || true
docker run -d --name openflare-agent --restart unless-stopped \
-p 80:80 -p 443:443 \
-p 80:80 -p 443:443/tcp -p 443:443/udp \
-v openflare-agent-data:/data \
-e OPENFLARE_SERVER_URL=http://your-server:3000 \
-e OPENFLARE_AGENT_TOKEN=YOUR_AGENT_TOKEN \
+14 -7
View File
@@ -12,7 +12,7 @@
"rules": [
{
"name": "单 IP 404 高频扫描",
"expr": "request_count > 100 && status_404_ratio >= 0.8"
"expr": "request_count > 100 && StatusRatio(404) >= 0.8"
}
]
}
@@ -57,6 +57,13 @@ Host 是否为“通过 IP 访问”按请求日志中的 `Host` 字段判断:
比例字段都是 `0` 到 `1` 之间的小数。80% 应写成 `0.8`,50% 应写成 `0.5`。
### 自定义状态码匹配方法
如果内置的 `status_404_count` 和 `status_404_ratio` 不能满足您的需求,您可以使用以下内置方法来匹配任意状态码的请求数与占比:
* **`StatusCount(code)`**: 获取当前 IP 在回看窗口内返回指定状态码的请求数(如 `StatusCount(403) > 10`)
* **`StatusRatio(code)`**: 获取当前 IP 在回看窗口内返回指定状态码的请求数占该 IP 总请求数的比例(如 `StatusRatio(502) >= 0.5`)
## Expr 常用写法
自动 IP 组使用 Expr 语法,当前表达式必须返回布尔值。
@@ -67,12 +74,12 @@ Host 是否为“通过 IP 访问”按请求日志中的 `Host` 字段判断:
| --- | --- | --- |
| `>`、`>=`、`<`、`<=` | 数值比较 | `request_count > 100` |
| `==`、`!=` | 相等或不相等 | `ip != "127.0.0.1"` |
| `&&` | 并且 | `request_count > 100 && status_404_ratio >= 0.8` |
| `||` | 或者 | `status_404_ratio >= 0.8 || server_error_count > 20` |
| `&&` | 并且 | `request_count > 100 && StatusRatio(404) >= 0.8` |
| `||` | 或者 | `StatusRatio(404) >= 0.8 || server_error_count > 20` |
| `!` | 取反 | `!(ip == "127.0.0.1")` |
| `in` | 判断值是否在列表中 | `ip in ["203.0.113.10", "198.51.100.20"]` |
| `not in` | 判断值是否不在列表中 | `ip not in ["127.0.0.1"]` |
| `()` | 分组控制优先级 | `(request_count > 100 && status_404_ratio >= 0.8) || server_error_count > 50` |
| `()` | 分组控制优先级 | `(request_count > 100 && StatusRatio(404) >= 0.8) || server_error_count > 50` |
## 内置预设
@@ -81,7 +88,7 @@ Host 是否为“通过 IP 访问”按请求日志中的 `Host` 字段判断:
```json
{
"name": "单 IP 404 高频扫描",
"expr": "request_count > 100 && status_404_ratio >= 0.8"
"expr": "request_count > 100 && StatusRatio(404) >= 0.8"
}
```
@@ -106,7 +113,7 @@ Host 是否为“通过 IP 访问”按请求日志中的 `Host` 字段判断:
"rules": [
{
"name": "高频 404 扫描",
"expr": "request_count > 100 && status_404_ratio >= 0.8"
"expr": "request_count > 100 && StatusRatio(404) >= 0.8"
}
]
}
@@ -148,7 +155,7 @@ IP 直连访问异常:
"rules": [
{
"name": "排除可信 IP 的 404 扫描",
"expr": "ip not in [\"203.0.113.10\", \"198.51.100.20\"] && request_count > 100 && status_404_ratio >= 0.8"
"expr": "ip not in [\"203.0.113.10\", \"198.51.100.20\"] && request_count > 100 && StatusRatio(404) >= 0.8"
}
]
}
+1 -1
View File
@@ -48,7 +48,7 @@ IP 组是进行大批量 IP 过滤的基石。OpenFlare 提供了极富弹性的
#### 3. 自动 IP 组 (Automatic)
* **用途**:**最具杀伤力的防扫描、防爆破自动通道**。
* **配置**:类型选择「自动」-> 编写 Expr 日志聚合逻辑。你可以直接引用系统内置的预设:
* **单 IP 404 高频扫描**:`request_count > 100 && status_404_ratio >= 0.8` (单个 IP 最近一小时请求超 100 次且 404 响应占比超 80%)。
* **单 IP 404 高频扫描**:`request_count > 100 && StatusRatio(404) >= 0.8` (单个 IP 最近一小时请求超 100 次且 404 响应占比超 80%)。
* **单 IP 直连访问异常**:`ip_host_count > 50 && ip_host_ratio > 0.5` (绕过域名直接通过 IP 地址进行高频请求)。
* **测试与立即执行**:保存前可点击 **「测试规则」** 按钮预览当前日志窗口被命中的 IP。保存后可点击 **「立即执行」** 直接聚合日志并生成封禁名单。
+1 -17
View File
@@ -41,23 +41,7 @@ OpenFlare 的管理端 API 与 Agent API 都使用 JSON。
| `POST` | `/api/waf/ip-groups/:id/delete` | 删除 IP 组;已被规则组引用时会拒绝 |
| `POST` | `/api/waf/ip-groups/:id/sync` | 立即同步订阅型 IP 组或立即执行自动型 IP 组 |
IP 组 `type` 支持 `manual`、`automatic`、`subscription`。自动型 IP 组的 `auto_config` 是 JSON 对象,当前支持:
```json
{
"lookback_minutes": 60,
"rules": [
{
"name": "单 IP 404 高频扫描",
"expr": "request_count > 100 && status_404_ratio >= 0.8"
},
{
"name": "单 IP 直连访问异常",
"expr": "ip_host_count > 50 && ip_host_ratio > 0.5"
}
]
}
```
IP 组 `type` 支持 `manual`、`automatic`、`subscription`。自动型 IP 组的 `auto_config` 是 JSON 对象
自动规则使用 Expr 语法,表达式必须返回布尔值。规则按单个 IP 的请求日志聚合指标计算,可用字段包括 `ip`、`request_count`、`status_404_count`、`status_404_ratio`、`ip_host_count`、`ip_host_ratio`、`client_error_count`、`server_error_count`、`last_seen_unix`。完整语法和字段含义见 [WAF 自动 IP 组规则语法](../guide/waf-ip-group-expr.md)。订阅格式支持 `text` 与 `json`:文本格式按行解析 IP/IP 段并忽略空行和 `#` 开头的注释;JSON 格式可通过映射规则选择数组,默认读取根数组。
+27 -8
View File
@@ -236,8 +236,27 @@ local challenge_info = cjson.encode({
pow_challenges:set(challenge_id, challenge_info, challenge_ttl)
local static_prefix = "/.within.website/x/cmd/anubis/static/"
local title = "Making sure you're not a bot!"
local accept_lang = ngx.var.http_accept_language or ""
local lang = "en"
if string.find(accept_lang, "zh") then
lang = "zh-CN"
end
local t_title = "Making sure you're not a bot!"
local t_status = "Loading..."
local t_protected = "This site is protected by a Proof-of-Work challenge. Your browser will solve a small puzzle before the upstream response is shown."
local t_why = "Why am I seeing this?"
local t_why_desc = "OpenFlare is asking your browser to complete a lightweight computation to distinguish normal browser traffic from automated abuse. This should finish automatically."
local t_noscript = "JavaScript is required to pass this verification. Please enable JavaScript and reload."
if lang == "zh-CN" then
t_title = "正在确认你是不是机器人!"
t_status = "加载中..."
t_protected = "本网站受工作量证明(Proof-of-Work)挑战保护。在显示源站响应之前,您的浏览器将解决一个微型谜题。"
t_why = "为什么我会看到这个?"
t_why_desc = "OpenFlare 正在要求您的浏览器完成一项轻量级计算,以区分正常的浏览器流量和自动化的恶意请求。这应该会自动完成。"
t_noscript = "很遗憾,您必须启用 JavaScript 才能通过这项验证。请开启 JavaScript 并刷新页面。"
end
ngx.header.content_type = "text/html; charset=utf-8"
ngx.say([[<!DOCTYPE html>
@@ -246,7 +265,7 @@ ngx.say([[<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title>]] .. title .. [[</title>
<title>]] .. t_title .. [[</title>
<link rel="stylesheet" href="]] .. static_prefix .. [[css/xess.css">
<style>
body,html{height:100%;display:flex;justify-content:center;align-items:center;margin-left:auto;margin-right:auto}
@@ -272,17 +291,17 @@ body,html{height:100%;display:flex;justify-content:center;align-items:center;mar
</head>
<body id="top">
<main>
<h1 id="title" class="centered-div">]] .. title .. [[</h1>
<h1 id="title" class="centered-div">]] .. t_title .. [[</h1>
<div class="centered-div">
<img id="image" style="width:100%;max-width:256px;" src="]] .. static_prefix .. [[img/pensive.webp?cacheBuster=openflare-pow">
<p id="status">Loading...</p>
<p>This site is protected by a Proof-of-Work challenge. Your browser will solve a small puzzle before the upstream response is shown.</p>
<p id="status">]] .. t_status .. [[</p>
<p>]] .. t_protected .. [[</p>
<div id="progress" role="progressbar" aria-labelledby="status"><div class="bar-inner"></div></div>
<details>
<summary>Why am I seeing this?</summary>
<p>OpenFlare is asking your browser to complete a lightweight computation to distinguish normal browser traffic from automated abuse. This should finish automatically.</p>
<summary>]] .. t_why .. [[</summary>
<p>]] .. t_why_desc .. [[</p>
</details>
<noscript><p>JavaScript is required to pass this verification. Please enable JavaScript and reload.</p></noscript>
<noscript><p>]] .. t_noscript .. [[</p></noscript>
</div>
</main>
<script type="module" src="]] .. static_prefix .. [[js/main.mjs"></script>
+1
View File
@@ -77,6 +77,7 @@ var OpenRestyProxyConnectTimeout = 3
var OpenRestyProxySendTimeout = 60
var OpenRestyProxyReadTimeout = 60
var OpenRestyWebsocketEnabled = true
var OpenRestyHTTP3Enabled = true
var OpenRestyProxyRequestBufferingEnabled = false
var OpenRestyProxyBufferingEnabled = true
var OpenRestyProxyBuffers = "16 16k"
+1
View File
@@ -159,6 +159,7 @@ func validateOpenRestyOption(key string, value string) error {
return nil
case "OpenRestyEventsMultiAcceptEnabled",
"OpenRestyWebsocketEnabled",
"OpenRestyHTTP3Enabled",
"OpenRestyProxyRequestBufferingEnabled",
"OpenRestyProxyBufferingEnabled",
"OpenRestyGzipEnabled",
+3
View File
@@ -70,6 +70,7 @@ func InitOptionMap() {
common.OptionMap["OpenRestyProxySendTimeout"] = strconv.Itoa(common.OpenRestyProxySendTimeout)
common.OptionMap["OpenRestyProxyReadTimeout"] = strconv.Itoa(common.OpenRestyProxyReadTimeout)
common.OptionMap["OpenRestyWebsocketEnabled"] = strconv.FormatBool(common.OpenRestyWebsocketEnabled)
common.OptionMap["OpenRestyHTTP3Enabled"] = strconv.FormatBool(common.OpenRestyHTTP3Enabled)
common.OptionMap["OpenRestyProxyRequestBufferingEnabled"] = strconv.FormatBool(common.OpenRestyProxyRequestBufferingEnabled)
common.OptionMap["OpenRestyProxyBufferingEnabled"] = strconv.FormatBool(common.OpenRestyProxyBufferingEnabled)
common.OptionMap["OpenRestyProxyBuffers"] = common.OpenRestyProxyBuffers
@@ -278,6 +279,8 @@ func updateOptionMap(key string, value string) {
}
case "OpenRestyWebsocketEnabled":
common.OpenRestyWebsocketEnabled = value == "true"
case "OpenRestyHTTP3Enabled":
common.OpenRestyHTTP3Enabled = value == "true"
case "OpenRestyProxyRequestBufferingEnabled":
common.OpenRestyProxyRequestBufferingEnabled = value == "true"
case "OpenRestyProxyBufferingEnabled":
@@ -152,6 +152,7 @@ type openRestyConfigSnapshot struct {
ProxySendTimeout int `json:"proxy_send_timeout"`
ProxyReadTimeout int `json:"proxy_read_timeout"`
WebsocketEnabled bool `json:"websocket_enabled"`
HTTP3Enabled bool `json:"http3_enabled"`
ProxyRequestBuffering bool `json:"proxy_request_buffering"`
ProxyBufferingEnabled bool `json:"proxy_buffering_enabled"`
ProxyBuffers string `json:"proxy_buffers"`
@@ -952,6 +953,7 @@ func buildOpenRestyConfigSnapshot() openRestyConfigSnapshot {
ProxySendTimeout: common.OpenRestyProxySendTimeout,
ProxyReadTimeout: common.OpenRestyProxyReadTimeout,
WebsocketEnabled: common.OpenRestyWebsocketEnabled,
HTTP3Enabled: common.OpenRestyHTTP3Enabled,
ProxyRequestBuffering: common.OpenRestyProxyRequestBufferingEnabled,
ProxyBufferingEnabled: common.OpenRestyProxyBufferingEnabled,
ProxyBuffers: common.OpenRestyProxyBuffers,
@@ -1071,6 +1073,7 @@ func diffOpenRestyOptionDetails(left openRestyConfigSnapshot, right openRestyCon
appendIfChanged("OpenRestyProxySendTimeout", fmt.Sprintf("%d", left.ProxySendTimeout), fmt.Sprintf("%d", right.ProxySendTimeout))
appendIfChanged("OpenRestyProxyReadTimeout", fmt.Sprintf("%d", left.ProxyReadTimeout), fmt.Sprintf("%d", right.ProxyReadTimeout))
appendIfChanged("OpenRestyWebsocketEnabled", fmt.Sprintf("%t", left.WebsocketEnabled), fmt.Sprintf("%t", right.WebsocketEnabled))
appendIfChanged("OpenRestyHTTP3Enabled", fmt.Sprintf("%t", left.HTTP3Enabled), fmt.Sprintf("%t", right.HTTP3Enabled))
appendIfChanged("OpenRestyProxyRequestBufferingEnabled", fmt.Sprintf("%t", left.ProxyRequestBuffering), fmt.Sprintf("%t", right.ProxyRequestBuffering))
appendIfChanged("OpenRestyProxyBufferingEnabled", fmt.Sprintf("%t", left.ProxyBufferingEnabled), fmt.Sprintf("%t", right.ProxyBufferingEnabled))
appendIfChanged("OpenRestyProxyBuffers", left.ProxyBuffers, right.ProxyBuffers)
@@ -1119,6 +1122,7 @@ func openRestyOptionKeys() []string {
"OpenRestyProxySendTimeout",
"OpenRestyProxyReadTimeout",
"OpenRestyWebsocketEnabled",
"OpenRestyHTTP3Enabled",
"OpenRestyProxyRequestBufferingEnabled",
"OpenRestyProxyBufferingEnabled",
"OpenRestyProxyBuffers",
@@ -489,6 +489,9 @@ func TestPublishConfigVersionRendersMultipleCertificatesForMultiDomainWebsite(t
func TestPublishConfigVersionSkipsHTTPSForDomainsWithoutCertificate(t *testing.T) {
setupServiceTestDB(t)
if err := model.UpdateOption("OpenRestyHTTP3Enabled", "false"); err != nil {
t.Fatalf("UpdateOption failed: %v", err)
}
appCertPEM, appKeyPEM := generateCertificatePair(t, []string{"app.example.com"})
appCertificate, err := CreateTLSCertificate(TLSCertificateInput{
@@ -1338,6 +1341,80 @@ func TestOpenRestyProxyRequestBufferingDefaultsToOff(t *testing.T) {
}
}
func TestPreviewConfigVersionSupportsHTTP3(t *testing.T) {
setupServiceTestDB(t)
appCertPEM, appKeyPEM := generateCertificatePair(t, []string{"h3.example.com"})
appCertificate, err := CreateTLSCertificate(TLSCertificateInput{
Name: "h3-cert",
CertPEM: appCertPEM,
KeyPEM: appKeyPEM,
})
if err != nil {
t.Fatalf("CreateTLSCertificate failed: %v", err)
}
_, err = CreateProxyRoute(ProxyRouteInput{
SiteName: "h3-site",
Domains: []string{"h3.example.com"},
OriginURL: "https://origin.internal",
Enabled: true,
EnableHTTPS: true,
CertID: &appCertificate.ID,
DomainCertIDs: []uint{appCertificate.ID},
})
if err != nil {
t.Fatalf("CreateProxyRoute failed: %v", err)
}
if err := model.UpdateOption("OpenRestyHTTP3Enabled", "true"); err != nil {
t.Fatalf("UpdateOption OpenRestyHTTP3Enabled failed: %v", err)
}
preview, err := PreviewConfigVersion()
if err != nil {
t.Fatalf("PreviewConfigVersion failed: %v", err)
}
if !strings.Contains(preview.MainConfig, "listen 443 ssl default_server;\n listen 443 quic reuseport default_server;") {
t.Fatalf("expected default server block to contain quic reuseport listener, main config: %s", preview.MainConfig)
}
if !strings.Contains(preview.RenderedConfig, "listen 443 quic;") {
t.Fatalf("expected routing server block to contain listen 443 quic, rendered config: %s", preview.RenderedConfig)
}
if !strings.Contains(preview.RenderedConfig, "add_header Alt-Svc 'h3=\":443\"; ma=86400';") {
t.Fatalf("expected routing server block to contain Alt-Svc header, rendered config: %s", preview.RenderedConfig)
}
if !strings.Contains(preview.RenderedConfig, "listen 443 ssl;") {
t.Fatal("expected standard listen 443 ssl to be preserved")
}
if !strings.Contains(preview.RenderedConfig, "http2 on;") {
t.Fatal("expected standard http2 on to be preserved")
}
if err := model.UpdateOption("OpenRestyHTTP3Enabled", "false"); err != nil {
t.Fatalf("UpdateOption OpenRestyHTTP3Enabled failed: %v", err)
}
previewOff, err := PreviewConfigVersion()
if err != nil {
t.Fatalf("PreviewConfigVersion failed: %v", err)
}
if strings.Contains(previewOff.MainConfig, "listen 443 quic reuseport default_server;") {
t.Fatal("expected default server block to omit quic listener when disabled")
}
if strings.Contains(previewOff.RenderedConfig, "listen 443 quic;") {
t.Fatal("expected routing server block to omit quic listener when disabled")
}
if strings.Contains(previewOff.RenderedConfig, "add_header Alt-Svc") {
t.Fatal("expected routing server block to omit Alt-Svc header when disabled")
}
}
func setupServiceTestDB(t *testing.T) {
t.Helper()
nodeAccessTokenCache.reset()
+22 -1
View File
@@ -69,6 +69,21 @@ type wafIPGroupAutoRuleEnv struct {
ClientErrorCount int `expr:"client_error_count"`
ServerErrorCount int `expr:"server_error_count"`
LastSeenUnix int64 `expr:"last_seen_unix"`
statusCounts map[int]int
}
func (env wafIPGroupAutoRuleEnv) StatusCount(code int) int {
if env.statusCounts == nil {
return 0
}
return env.statusCounts[code]
}
func (env wafIPGroupAutoRuleEnv) StatusRatio(code int) float64 {
if env.RequestCount <= 0 || env.statusCounts == nil {
return 0.0
}
return float64(env.statusCounts[code]) / float64(env.RequestCount)
}
type wafIPGroupAutoAccumulator struct {
@@ -79,6 +94,7 @@ type wafIPGroupAutoAccumulator struct {
clientErrorCount int
serverErrorCount int
lastSeen time.Time
statusCounts map[int]int
}
type WAFIPGroupInput struct {
@@ -755,10 +771,14 @@ func evaluateParsedWAFIPGroupAutoConfig(config wafIPGroupAutoConfig, now time.Ti
}
acc := accumulators[ip]
if acc == nil {
acc = &wafIPGroupAutoAccumulator{ip: ip}
acc = &wafIPGroupAutoAccumulator{
ip: ip,
statusCounts: make(map[int]int),
}
accumulators[ip] = acc
}
acc.requestCount++
acc.statusCounts[item.StatusCode]++
if item.StatusCode == http.StatusNotFound {
acc.status404Count++
}
@@ -800,6 +820,7 @@ func (acc *wafIPGroupAutoAccumulator) toExprEnv() wafIPGroupAutoRuleEnv {
IPHostCount: acc.ipHostCount,
ClientErrorCount: acc.clientErrorCount,
ServerErrorCount: acc.serverErrorCount,
statusCounts: acc.statusCounts,
}
if acc.requestCount > 0 {
env.Status404Ratio = float64(acc.status404Count) / float64(acc.requestCount)
+50 -3
View File
@@ -228,7 +228,7 @@ func TestSyncWAFIPGroupAutomaticExprRules(t *testing.T) {
AutoConfig: json.RawMessage(`{
"lookback_minutes": 60,
"rules": [
{"name":"单 IP 404 高频扫描","expr":"request_count > 100 && status_404_ratio >= 0.8"},
{"name":"单 IP 404 高频扫描","expr":"request_count > 100 && StatusRatio(404) >= 0.8"},
{"name":"单 IP 直连访问异常","expr":"ip_host_count > 50 && ip_host_ratio > 0.5"}
]
}`),
@@ -267,7 +267,7 @@ func TestWAFIPGroupAutoConfigReturnsMatchedIPs(t *testing.T) {
AutoConfig: json.RawMessage(`{
"lookback_minutes": 60,
"rules": [
{"name":"单 IP 404 高频扫描","expr":"request_count > 100 && status_404_ratio >= 0.8"},
{"name":"单 IP 404 高频扫描","expr":"request_count > 100 && StatusRatio(404) >= 0.8"},
{"name":"单 IP 直连访问异常","expr":"ip_host_count > 50 && ip_host_ratio > 0.5"}
]
}`),
@@ -383,7 +383,7 @@ func TestWAFIPGroupAutomaticTTLExpiration(t *testing.T) {
"lookback_minutes": 60,
"ttl": 10,
"rules": [
{"name":"404 Scan","expr":"request_count > 100 && status_404_ratio >= 0.8"}
{"name":"404 Scan","expr":"request_count > 100 && StatusRatio(404) >= 0.8"}
]
}`),
})
@@ -464,3 +464,50 @@ func seedWAFNodeAccessLogs(t *testing.T, loggedAt time.Time, remoteAddr string,
}
}
}
func TestSyncWAFIPGroupAutomaticCustomStatusRules(t *testing.T) {
setupServiceTestDB(t)
now := time.Now().UTC()
// Seed 10 requests from 203.0.113.50, where 3 return 403, 7 return 200
seedWAFNodeAccessLogsWithStatus(t, now, "203.0.113.50", "app.example.com", 7, http.StatusOK)
seedWAFNodeAccessLogsWithStatus(t, now, "203.0.113.50", "app.example.com", 3, http.StatusForbidden)
group, err := CreateWAFIPGroup(WAFIPGroupInput{
Name: "custom status code blacklist",
Type: WAFIPGroupTypeAutomatic,
Enabled: true,
AutoConfig: json.RawMessage(`{
"lookback_minutes": 60,
"rules": [
{"name":"高频 403 探测","expr":"StatusCount(403) >= 3 && StatusRatio(403) >= 0.3"}
]
}`),
})
if err != nil {
t.Fatalf("CreateWAFIPGroup failed: %v", err)
}
result, err := SyncWAFIPGroup(group.ID)
if err != nil {
t.Fatalf("SyncWAFIPGroup failed: %v", err)
}
if result.IPCount != 1 || result.Group.IPList[0] != "203.0.113.50" {
t.Fatalf("expected 203.0.113.50 to be matched, got %#v", result)
}
}
func seedWAFNodeAccessLogsWithStatus(t *testing.T, loggedAt time.Time, remoteAddr string, host string, count int, statusCode int) {
t.Helper()
for i := 0; i < count; i++ {
if err := model.DB.Create(&model.NodeAccessLog{
NodeID: "node-waf-auto",
LoggedAt: loggedAt.Add(-time.Duration(i%30) * time.Second),
RemoteAddr: remoteAddr,
Host: host,
Path: "/probe",
StatusCode: statusCode,
}).Error; err != nil {
t.Fatalf("failed to seed access log: %v", err)
}
}
}
@@ -305,7 +305,7 @@ func renderMainConfigTemplate(templateText string, cfg ConfigSnapshot) string {
"{{OpenRestyWorkerConnections}}", fmt.Sprintf("%d", cfg.WorkerConnections),
"{{OpenRestyWorkerRlimitNofile}}", fmt.Sprintf("%d", cfg.WorkerRlimitNofile),
"{{OpenRestyConnectionUpgradeMap}}", renderConnectionUpgradeMap(),
"{{OpenRestyDefaultServerBlock}}", renderDefaultServerBlock(cfg.DefaultServerReturnStatus),
"{{OpenRestyDefaultServerBlock}}", renderDefaultServerBlock(cfg.DefaultServerReturnStatus, cfg.HTTP3Enabled),
"{{OpenRestyAccessLogPath}}", AccessLogPlaceholder,
"{{OpenRestyErrorLogPath}}", ErrorLogPlaceholder,
"{{OpenRestyEventsUseDirective}}", renderTemplateDirective(cfg.EventsUse != "", fmt.Sprintf("use %s;", cfg.EventsUse)),
@@ -379,7 +379,13 @@ func renderHTTPRedirectServer(serverNames string) string {
func renderHTTPSServer(serverNames string, siteName string, originURL string, originHost string, certificateID uint, customHeaders []CustomHeader, cacheConfig routeCacheConfig, limitConfig routeLimitConfig, upstreamConfig routeUpstreamConfig, powEnabled bool, basicAuthEnabled bool, basicAuthUsername string, basicAuthPassword string, cfg ConfigSnapshot) string {
certPath := fmt.Sprintf("%s/%d.crt", CertDirPlaceholder, certificateID)
keyPath := fmt.Sprintf("%s/%d.key", CertDirPlaceholder, certificateID)
return fmt.Sprintf("server {\n listen 443 ssl;\n http2 on;\n server_name %s;\n ssl_certificate %s;\n ssl_certificate_key %s;\n%s%s location / {\n%s%s%s%s%s }\n%s}\n\n", serverNames, certPath, keyPath, renderAccessBlock(siteName, powEnabled), renderPowLocationBlocks(powEnabled), renderBasicAuthBlock(basicAuthEnabled, basicAuthUsername, basicAuthPassword), renderProxyHeaderBlock(originURL, originHost, customHeaders, upstreamConfig, cfg), renderRouteLimitBlock(limitConfig), renderRouteCacheBlock(cacheConfig, cfg), renderProxyPassBlock(originURL, upstreamConfig), renderPowStaticLocationBlock(powEnabled))
var h3Listen string
var h3Header string
if cfg.HTTP3Enabled {
h3Listen = " listen 443 quic;\n"
h3Header = " add_header Alt-Svc 'h3=\":443\"; ma=86400';\n"
}
return fmt.Sprintf("server {\n listen 443 ssl;\n%s http2 on;\n server_name %s;\n ssl_certificate %s;\n ssl_certificate_key %s;\n%s%s%s location / {\n%s%s%s%s%s }\n%s}\n\n", h3Listen, serverNames, certPath, keyPath, h3Header, renderAccessBlock(siteName, powEnabled), renderPowLocationBlocks(powEnabled), renderBasicAuthBlock(basicAuthEnabled, basicAuthUsername, basicAuthPassword), renderProxyHeaderBlock(originURL, originHost, customHeaders, upstreamConfig, cfg), renderRouteLimitBlock(limitConfig), renderRouteCacheBlock(cacheConfig, cfg), renderProxyPassBlock(originURL, upstreamConfig), renderPowStaticLocationBlock(powEnabled))
}
func renderProxyHeaderBlock(originURL string, originHost string, customHeaders []CustomHeader, upstreamConfig routeUpstreamConfig, cfg ConfigSnapshot) string {
@@ -586,10 +592,14 @@ func renderConnectionUpgradeMap() string {
return " map $http_upgrade $connection_upgrade {\n default upgrade;\n '' \"\";\n }\n\n"
}
func renderDefaultServerBlock(statusCode int) string {
func renderDefaultServerBlock(statusCode int, http3Enabled bool) string {
if statusCode <= 0 {
statusCode = 421
}
var h3Default string
if http3Enabled {
h3Default = "\n listen 443 quic reuseport default_server;"
}
return strings.Join([]string{
" server {",
" listen 80 default_server;",
@@ -599,7 +609,7 @@ func renderDefaultServerBlock(statusCode int) string {
" }",
"",
" server {",
" listen 443 ssl default_server;",
fmt.Sprintf(" listen 443 ssl default_server;%s", h3Default),
" server_name _;",
"",
" ssl_reject_handshake on;",
@@ -175,6 +175,7 @@ type ConfigSnapshot struct {
ProxySendTimeout int `json:"proxy_send_timeout"`
ProxyReadTimeout int `json:"proxy_read_timeout"`
WebsocketEnabled bool `json:"websocket_enabled"`
HTTP3Enabled bool `json:"http3_enabled"`
ProxyRequestBuffering bool `json:"proxy_request_buffering"`
ProxyBufferingEnabled bool `json:"proxy_buffering_enabled"`
ProxyBuffers string `json:"proxy_buffers"`
+1 -1
View File
@@ -211,7 +211,7 @@ export function buildNodeDockerInstallCommand(
`docker pull ${image}`,
`docker rm -f openflare-agent 2>/dev/null || true`,
`docker run -d --name openflare-agent --restart unless-stopped \\`,
` -p 80:80 -p 443:443 \\`,
` -p 80:80 -p 443:443/tcp -p 443:443/udp \\`,
` -e OPENFLARE_SERVER_URL=${serverUrl} \\`,
` -e OPENFLARE_AGENT_TOKEN=${agentToken} \\`,
` ${image}`,
@@ -48,6 +48,7 @@ const defaultPerformanceFields = {
OpenRestyProxySendTimeout: '60',
OpenRestyProxyReadTimeout: '60',
OpenRestyWebsocketEnabled: true,
OpenRestyHTTP3Enabled: true,
OpenRestyProxyRequestBufferingEnabled: false,
OpenRestyProxyBufferingEnabled: true,
OpenRestyProxyBuffers: '16 16k',
@@ -96,6 +97,7 @@ const performanceFieldTooltips: Record<string, string> = {
proxy_read_timeout: '等待上游返回响应的超时时间,单位秒。',
websocket:
'控制是否为反向代理规则自动注入 WebSocket 升级所需的 HTTP/1.1、Upgrade 和 Connection 头。',
http3: '启用后,OpenResty 将在 443 端口启用 HTTP/3 (QUIC) 协议支持。',
proxy_request_buffering:
'控制请求体是否先在 Nginx 侧缓冲后再转发给上游,上传和流式场景经常会用到。',
proxy_buffering:
@@ -233,6 +235,10 @@ export function PerformancePage() {
optionMap.OpenRestyWebsocketEnabled,
true,
),
OpenRestyHTTP3Enabled: toBoolean(
optionMap.OpenRestyHTTP3Enabled,
false,
),
OpenRestyProxyRequestBufferingEnabled: toBoolean(
optionMap.OpenRestyProxyRequestBufferingEnabled,
false,
@@ -450,6 +456,10 @@ export function PerformancePage() {
'OpenRestyWebsocketEnabled',
String(performanceFields.OpenRestyWebsocketEnabled),
],
[
'OpenRestyHTTP3Enabled',
String(performanceFields.OpenRestyHTTP3Enabled),
],
[
'OpenRestyProxyRequestBufferingEnabled',
String(performanceFields.OpenRestyProxyRequestBufferingEnabled),
@@ -1008,6 +1018,17 @@ export function PerformancePage() {
}))
}
/>
<ToggleField
label="http3"
tooltip={performanceFieldTooltips.http3}
checked={performanceFields.OpenRestyHTTP3Enabled}
onChange={(checked) =>
setPerformanceFields((previous) => ({
...previous,
OpenRestyHTTP3Enabled: checked,
}))
}
/>
<ToggleField
label="proxy_request_buffering"
tooltip={performanceFieldTooltips.proxy_request_buffering}
@@ -75,7 +75,7 @@ const typeLabels: Record<WAFIPGroupType, string> = {
const automaticPresetRules = [
{
name: '单 IP 404 高频扫描',
expr: 'request_count > 100 && status_404_ratio >= 0.8',
expr: 'request_count > 100 && StatusRatio(404) >= 0.8',
},
{
name: '单 IP 直连访问异常',
@@ -587,7 +587,7 @@ export function WAFIPGroupsPage() {
</ResourceField>
<ResourceField
label="自动配置 JSON"
hint="可用字段:request_count、status_404_count、status_404_ratio、ip_host_count、ip_host_ratio。支持 ttl(秒,默认 -1 永久拉黑)。"
hint="可用字段:request_count、status_404_count、status_404_ratio、ip_host_count、ip_host_ratio。方法:StatusCount(code)、StatusRatio(code)。支持 ttl(秒,默认 -1 永久拉黑)。"
>
<ResourceTextarea
value={draft.auto_config_text}
@@ -200,7 +200,7 @@ describe('WAF IP groups', () => {
const textarea = screen.getByLabelText(/自动配置 JSON/);
const value = (textarea as HTMLTextAreaElement).value;
expect(value).toContain('request_count > 100 && status_404_ratio >= 0.8');
expect(value).toContain('request_count > 100 && StatusRatio(404) >= 0.8');
expect(value).toContain('ip_host_count > 50 && ip_host_ratio > 0.5');
});
@@ -260,7 +260,7 @@ describe('WAF IP groups', () => {
lookback_minutes: 60,
rules: [
expect.objectContaining({
expr: 'request_count > 100 && status_404_ratio >= 0.8',
expr: 'request_count > 100 && StatusRatio(404) >= 0.8',
}),
],
}),