Go / 系统课时

组装中间件与安全边界

组装中间件与安全边界

生产级 HTTP 服务需要让请求身份、访问日志、panic 恢复、请求体上限和认证按明确顺序协作。本节把这些边界组装成一条可运行链路,并用未认证、超限、panic 与正常请求验证每一层的截断位置和对外响应。

学习目标

  • 设计请求身份、访问日志、恢复、请求体限制与认证中间件的执行顺序
  • 在错误响应中保留追踪信息,同时避免令牌、Cookie 和请求体进入日志
  • 验证 401、413、500 与正常 200 路径都返回稳定结果

先确定中间件顺序

本例采用“请求 ID → 访问日志 → panic 恢复 → 请求体限制 → Bearer 认证 → 业务处理器”。请求 ID 必须先建立,后续日志和错误响应才能引用同一标识;访问日志包住其余链路以记录最终状态;恢复层覆盖业务侧 panic;体积限制尽早阻断过大输入;认证通过后才进入业务处理。

安全中间件执行顺序与失败截断点

组装一条可运行的安全链

下面的程序只依赖 Go 标准库。示例令牌固定为 demo-token,请求 ID 使用单调序号,均只用于本地验证;生产环境应从受控配置或密钥系统读取凭据,并采用满足全局唯一性要求的请求 ID 策略。

go
package main

import (
	"context"
	"crypto/subtle"
	"encoding/json"
	"errors"
	"io"
	"log"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

type contextKey string

const requestIDKey contextKey = "request-id"

var requestSequence atomic.Uint64

type middleware func(http.Handler) http.Handler

type responseRecorder struct {
	http.ResponseWriter
	status int
}

func (rec *responseRecorder) WriteHeader(code int) {
	if rec.status != 0 {
		return
	}
	rec.status = code
	rec.ResponseWriter.WriteHeader(code)
}

func (rec *responseRecorder) Write(p []byte) (int, error) {
	if rec.status == 0 {
		rec.WriteHeader(http.StatusOK)
	}
	return rec.ResponseWriter.Write(p)
}

type problem struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	RequestID string `json:"request_id"`
}

func requestIDFrom(req *http.Request) string {
	id, _ := req.Context().Value(requestIDKey).(string)
	return id
}

func writeProblem(writer http.ResponseWriter, req *http.Request, status int, code, message string) {
	headers := writer.Header()
	headers.Set("Content-Type", "application/json")
	writer.WriteHeader(status)
	_ = json.NewEncoder(writer).Encode(problem{
		Code:      code,
		Message:   message,
		RequestID: requestIDFrom(req),
	})
}

func requestID(next http.Handler) http.Handler {
	return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
		id := "req-" + strconv.FormatUint(requestSequence.Add(1), 10)
		writer.Header().Set("X-Request-ID", id)
		ctx := context.WithValue(req.Context(), requestIDKey, id)
		next.ServeHTTP(writer, req.WithContext(ctx))
	})
}

func accessLog(next http.Handler) http.Handler {
	return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
		rec := &responseRecorder{ResponseWriter: writer}
		defer func() {
			status := rec.status
			if status == 0 {
				status = http.StatusOK
			}
			// 只记录白名单字段,不记录认证头、Cookie、请求体或原始查询串。
			log.Printf("request_id=%s method=%s path=%s status=%d",
				requestIDFrom(req), req.Method, req.URL.Path, status)
		}()
		next.ServeHTTP(rec, req)
	})
}

func recoverPanic(next http.Handler) http.Handler {
	return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
		defer func() {
			if recover() != nil {
				log.Printf("request_id=%s event=panic_recovered", requestIDFrom(req))
				writeProblem(writer, req, http.StatusInternalServerError,
					"internal_error", "internal server error")
			}
		}()
		next.ServeHTTP(writer, req)
	})
}

func bodyLimit(maxBytes int64) middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
			if req.ContentLength > maxBytes {
				writeProblem(writer, req, http.StatusRequestEntityTooLarge,
					"payload_too_large", "request body exceeds limit")
				return
			}
			// Content-Length 缺失或不可信时,读取阶段仍由 MaxBytesReader 执行硬限制。
			req.Body = http.MaxBytesReader(writer, req.Body, maxBytes)
			next.ServeHTTP(writer, req)
		})
	}
}

func bearerAuth(next http.Handler) http.Handler {
	const expected = "Bearer demo-token"
	return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
		actual := req.Header.Get("Authorization")
		if subtle.ConstantTimeCompare([]byte(actual), []byte(expected)) != 1 {
			writeProblem(writer, req, http.StatusUnauthorized,
				"unauthorized", "missing or invalid bearer token")
			return
		}
		next.ServeHTTP(writer, req)
	})
}

func workHandler(writer http.ResponseWriter, req *http.Request) {
	body, err := io.ReadAll(req.Body)
	limitErr := (*http.MaxBytesError)(nil)
	if errors.As(err, &limitErr) && limitErr != nil {
		writeProblem(writer, req, http.StatusRequestEntityTooLarge,
			"payload_too_large", "request body exceeds limit")
		return
	}
	if err != nil {
		writeProblem(writer, req, http.StatusBadRequest,
			"invalid_body", "cannot read request body")
		return
	}

	writer.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(writer).Encode(struct {
		OK    bool `json:"ok"`
		Bytes int  `json:"bytes"`
	}{OK: true, Bytes: len(body)})
}

func chain(handler http.Handler, middlewares ...middleware) http.Handler {
	for i := len(middlewares) - 1; i >= 0; i-- {
		handler = middlewares[i](handler)
	}
	return handler
}

func main() {
	log.SetFlags(0)

	routes := http.NewServeMux()
	routes.HandleFunc("/work", workHandler)
	routes.HandleFunc("/panic", func(http.ResponseWriter, *http.Request) {
		panic("simulated failure")
	})

	handler := chain(
		routes,
		requestID,
		accessLog,
		recoverPanic,
		bodyLimit(1024),
		bearerAuth,
	)

	server := &http.Server{
		Addr:              "127.0.0.1:18080",
		Handler:           handler,
		ReadHeaderTimeout: 2 * time.Second,
		IdleTimeout:       30 * time.Second,
	}

	log.Println("listening on http://127.0.0.1:18080")
	log.Fatal(server.ListenAndServe())
}

预期输出

text
listening on http://127.0.0.1:18080

responseRecorder 让外层日志拿到最终状态码;它是教学版包装器,没有透传 Flusher、Hijacker 等可选接口。涉及流式响应、WebSocket 或其他高级协议能力时,应使用能保留这些接口的包装方案,而不是直接照搬这个最小实现。

验证四条请求路径

保存为 main.go 并执行 go run main.go 后,另开终端运行下面四个请求。请求 ID 每次启动都会重新计数,因此预期结果用 <ID> 表示实际值。

bash
curl -sS -w '\nHTTP %{http_code}\n' http://127.0.0.1:18080/work

printf 'x%.0s' {1..1100} | curl -sS -w '\nHTTP %{http_code}\n' \
  -H 'Authorization: Bearer demo-token' --data-binary @- http://127.0.0.1:18080/work

curl -sS -w '\nHTTP %{http_code}\n' \
  -H 'Authorization: Bearer demo-token' http://127.0.0.1:18080/panic

curl -sS -w '\nHTTP %{http_code}\n' \
  -H 'Authorization: Bearer demo-token' http://127.0.0.1:18080/work

预期结果

text
{"code":"unauthorized","message":"missing or invalid bearer token","request_id":"<ID>"}
HTTP 401
{"code":"payload_too_large","message":"request body exceeds limit","request_id":"<ID>"}
HTTP 413
{"code":"internal_error","message":"internal server error","request_id":"<ID>"}
HTTP 500
{"ok":true,"bytes":0}
HTTP 200

服务端访问日志只包含请求 ID、方法、路径和状态码;panic 路径还会额外记录 event=panic_recovered,但不会写出 panic 内容或 Bearer 令牌。这样既保留故障定位线索,也避免把认证凭据带入日志。

明确每一层的安全边界

recover 只能捕获同一 goroutine 中向上传播的 panic;如果处理器已经写出响应头或部分响应体,恢复层也无法可靠把已发送内容改成全新的 500 响应。流式响应因此需要单独设计错误策略,不能把恢复中间件当作事务回滚。

请求体限制只控制单次 HTTP 消息的读取规模,不能替代读取超时、反向代理上限和业务字段校验。认证中间件也只负责判断请求能否进入受保护处理器,针对具体资源和动作的授权仍应放在业务边界。把这些职责拆开并按顺序组装后,异常请求会在最合适的层级被截断,而业务处理器只处理已经通过基础安全检查的正常路径。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

组装中间件与安全边界

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通