53 lines
1.8 KiB
Go
53 lines
1.8 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
func TestSecurityHeadersAndCORS(t *testing.T) {
|
|
server := (&Server{AllowedOrigins: []string{"https://packages.example.com"}}).Handler()
|
|
request := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
|
request.Header.Set("Origin", "https://packages.example.com")
|
|
response := httptest.NewRecorder()
|
|
server.ServeHTTP(response, request)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("健康检查状态错误: %d", response.Code)
|
|
}
|
|
if response.Header().Get("Access-Control-Allow-Origin") != "https://packages.example.com" {
|
|
t.Fatal("允许来源响应头错误")
|
|
}
|
|
if response.Header().Get("X-Content-Type-Options") != "nosniff" {
|
|
t.Fatal("安全响应头缺失")
|
|
}
|
|
}
|
|
|
|
func TestHostGuardRejectsUnknownHost(t *testing.T) {
|
|
server := (&Server{AllowedHosts: []string{"packages.example.com"}}).Handler()
|
|
request := httptest.NewRequest(http.MethodGet, "http://unknown.example.com/healthz", nil)
|
|
response := httptest.NewRecorder()
|
|
server.ServeHTTP(response, request)
|
|
if response.Code != http.StatusMisdirectedRequest {
|
|
t.Fatalf("未知主机状态错误: %d", response.Code)
|
|
}
|
|
}
|
|
|
|
func TestRateLimit(t *testing.T) {
|
|
server := (&Server{RateLimitPerMinute: 1}).Handler()
|
|
first := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
|
first.RemoteAddr = "192.0.2.10:1234"
|
|
firstResponse := httptest.NewRecorder()
|
|
server.ServeHTTP(firstResponse, first)
|
|
if firstResponse.Code != http.StatusOK {
|
|
t.Fatalf("首次请求状态错误: %d", firstResponse.Code)
|
|
}
|
|
second := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
|
second.RemoteAddr = "192.0.2.10:5678"
|
|
secondResponse := httptest.NewRecorder()
|
|
server.ServeHTTP(secondResponse, second)
|
|
if secondResponse.Code != http.StatusTooManyRequests {
|
|
t.Fatalf("限流状态错误: %d", secondResponse.Code)
|
|
}
|
|
}
|