当 GraphQL 深度超过 10 时返回 400 的校验中间件

解读

在国内一线/二线互联网公司的 Go 后端面试中,GraphQL 深度限制是高频安全考点。
面试官真正想验证的是:

  1. 你是否意识到无限制嵌套查询会导致 CPU 暴涨、内存溢出,甚至被恶意 DoS;
  2. 能否用Negroni 中间件在业务 Handler 执行前完成只读、无副作用的校验,并立即 400 拒绝;
  3. 是否熟悉 Go 的 net/http 请求读取与Body 复用技巧,保证后续 Handler 仍能正常读取;
  4. 是否具备防御式编程思维:超时控制、内存上限、错误日志规范。

因此,题目隐含要求:

  • 不依赖第三方 GraphQL 库,纯标准库实现;
  • 深度阈值可配置;
  • 失败路径不回写业务日志,直接返回 JSON {"code":400,"msg":"query depth exceeds 10"};
  • 通过Negroni 洋葱模型插入,保持与业务零耦合。

知识点

  1. Negroni 中间件签名
    func(http.ResponseWriter, *http.Request, http.HandlerFunc)
    执行顺序:Wrap 后先正序再逆序,但本题只需前置拦截,故调用 next 前 return 即可。

  2. http.Request.Body 复用
    io.TeeReader + bytes.Buffer 把 Body 内容备份,校验完后用 ioutil.NopCloser 重新赋值,保证后续 json.Decode 或 graphql-go 能再次读取。

  3. GraphQL 深度计算
    仅解析query字段,忽略 variables;
    采用递归下降扫描 { 与 },遇到 fragment spread 需内联展开(面试现场可简化成只算字面 { 深度,但需说明生产环境要用 AST)。

  4. 性能与安全

    • 设置单次最大读取 2 MB,超量直接 413;
    • 设置解析超时 100 ms,防止巨型查询阻塞;
    • 深度阈值通过构造参数注入,单元测试可改 3 或 5。
  5. 日志规范
    校验失败只打一条 Warn,包含 X-Request-ID,避免日志轰炸;
    成功路径无日志,符合中间件无侵入原则。

答案

package negroni

import (
    "bytes"
    "context"
    "encoding/json"
    "errors"
    "io"
    "io/ioutil"
    "net/http"
    "strings"
    "time"
)

type MaxDepthConfig struct {
    MaxDepth      int           // 阈值,默认 10
    MaxBytes      int64         // 最大读取 2 MB
    ParseTimeout  time.Duration // 默认 100 ms
    ErrorResponse interface{}   // 返回体,可定制
}

func NewGraphQLDepthLimit(cfg MaxDepthConfig) negroni.Handler {
    if cfg.MaxDepth <= 0 {
        cfg.MaxDepth = 10
    }
    if cfg.MaxBytes <= 0 {
        cfg.MaxBytes = 2 << 20
    }
    if cfg.ParseTimeout <= 0 {
        cfg.ParseTimeout = 100 * time.Millisecond
    }
    if cfg.ErrorResponse == nil {
        cfg.ErrorResponse = map[string]interface{}{
            "code": 400,
            "msg":  "query depth exceeds limit",
        }
    }

    return negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
        // 只拦截 POST + /graphql
        if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/graphql") {
            next(w, r)
            return
        }

        // 限流读取
        limited := &io.LimitedReader{R: r.Body, N: cfg.MaxBytes + 1}
        buf := &bytes.Buffer{}
        if _, err := io.Copy(buf, limited); err != nil {
            http.Error(w, "read body error", 400)
            return
        }
        if limited.N == 0 {
            http.Error(w, "request too large", 413)
            return
        }

        // Body 复用
        r.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes()))

        // 解析 JSON
        var payload struct {
            Query string `json:"query"`
        }
        if err := json.NewDecoder(bytes.NewReader(buf.Bytes())).Decode(&payload); err != nil {
            http.Error(w, "invalid json", 400)
            return
        }

        // 计算深度
        ctx, cancel := context.WithTimeout(r.Context(), cfg.ParseTimeout)
        defer cancel()

        depth, err := calcDepth(ctx, payload.Query)
        if err != nil {
            http.Error(w, "parse timeout", 400)
            return
        }
        if depth > cfg.MaxDepth {
            w.Header().Set("Content-Type", "application/json; charset=utf-8")
            w.WriteHeader(400)
            json.NewEncoder(w).Encode(cfg.ErrorResponse)
            return
        }

        // 通过
        next(w, r)
    })
}

// 简易深度计算:只算字面 { 嵌套,忽略 fragment
func calcDepth(ctx context.Context, query string) (int, error) {
    query = strings.TrimSpace(query)
    maxDepth := 0
    depth := 0
    for i := 0; i < len(query); i++ {
        select {
        case <-ctx.Done():
            return 0, errors.New("timeout")
        default:
        }
        switch query[i] {
        case '{':
            depth++
            if depth > maxDepth {
                maxDepth = depth
            }
        case '}':
            depth--
            if depth < 0 {
                depth = 0
            }
        }
    }
    return maxDepth, nil
}

使用示例:

n := negroni.New()
n.Use(NewGraphQLDepthLimit(MaxDepthConfig{MaxDepth: 10}))
n.UseHandler(yourGraphQLHandler)
http.ListenAndServe(":8080", n)

拓展思考

  1. 生产级深度计算
    简易 { 计数无法处理 fragment 循环引用 和 inline spread,应引入 github.com/vektah/gqlparser/v2/ast 生成语法树,再后序遍历计算真实深度;同时把解析结果缓存到请求上下文,避免二次解析。

  2. 动态限深
    结合用户等级或AppKey做灰度:内部系统 20,外部开放 8;可把配置放到Apollo/Nacos,中间件热更新而不重启进程。

  3. 与 Negroni 错误恢复联动
    在校验失败时提前返回,不会触发 Recovery 中间件;若后续 Handler panic,仍由 Recovery 捕获,保证错误链清晰。

  4. 可观测性
    在拒绝场景下通过 prometheus.CounterVec 上报 graphql_depth_rejected_total{clientID},方便告警与运营分析。

  5. 深度+复杂度双维度
    国内大厂通常同时限制深度与字段复杂度(如 10 万),可再封装一个 GraphQLGuard 中间件,内部并行校验,任一超标即 400,形成立体防护网。