← 中文资源

简体中文版本

构建 WAF 规则引擎

构建 WAF 规则引擎:完整覆盖 web application firewalling,含 Rule loader、Pattern matcher 与测试的端到端实现。

阅读英文原文

项目概述

本项目实现一个面向 web application firewalling 的完整系统,核心要解决的问题是 evaluating request signatures against a rule set fast enough to sit in the hot path。整体由 Rule loader、Pattern matcher、Score accumulator、Action dispatcher、Rule hot-reload 五个模块组成,每个模块单一职责、可独立测试,最后通过集成测试验证端到端正确性。设计上把 a regex with catastrophic backtracking that turns a malicious request into a CPU denial of service 作为第一类需求先行处理,而非事后再补。

架构与关键决策

数据模型为 a compiled set of rules each with a pattern, a weight, and an action, evaluated in order with a running anomaly score。Rule loader 定义其余阶段共同依赖的数据形状并在边界处校验输入;Pattern matcher 承载 web application firewalling 的正确性逻辑;Score accumulator 专门处理 a regex with catastrophic backtracking that turns a malicious request into a CPU denial of service,在失败路径上给出明确的拒绝、重试或降级策略;Action dispatcher 提供可观测性,每次操作输出带关联 id 的结构化事件;Rule hot-reload 在过载时按既定方式降级,避免过载演变为数据损坏。配置与代码分离,使风险变更可经 diff 审阅。

实施与测试

按五个阶段依次实现 Rule loader、Pattern matcher、Score accumulator、Action dispatcher、Rule hot-reload,每阶段配套聚焦单测。集成测试组合各模块并驱动真实 web application firewalling 场景:先验证正常路径,再刻意触发 a regex with catastrophic backtracking that turns a malicious request into a CPU denial of service 并断言系统降级而非损坏。所有依赖均在进程内或被桩替换,用例在 CI 中确定可复现。

限制与后续

  • 单区域设计,多区域复制超出范围。
  • Rule loader 默认进程内,未水平共享。
  • 无鉴权层,假定部署在强制身份的边缘之后。

代码示例

# setup for waf-rule-engine
pnpm init
pnpm add fastify re2
pnpm add -D typescript tsx vitest
waf_rule_engine/
├── src/index.ts
├── src/rule-loader.ts
├── src/pattern-matcher.ts
├── tests/waf_rule_engine.test.ts
└── package.json
// Rule loader: web application firewalling core
export function ruleloader(input: RuleloaderInput): RuleloaderResult {
  // Build the rule loader that anchors web application firewalling and defines the core data shape.
  return processRuleloader(input);
}
// Pattern matcher — handles web application firewalling Add the pattern matcher so
export class Patternmatcher {
  constructor(private opts: PatternmatcherOptions) {}
  async run(ctx: Context): Promise<PatternmatcherOutput> {
    return this.execute(ctx);
  }
}
// Score accumulator: web application firewalling stage
export const scoreaccumulator = (next: Next) => async (req: Request) => {
  const out = await transform(req);
  return next(out);
};
// Action dispatcher for web application firewalling
export async function actiondispatcher(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
  let acc = init();
  for await (const c of stream) acc = merge(acc, c);
  return acc;
}
// Rule hot-reload: web application firewalling finalization
export function rulehotreload(state: State): Result {
  validate(state);
  return finalize(state);
}
# run the web application firewalling test suite
pnpm vitest run