接入托管域名HTTP验证与隔离挑战并补充回归用例
This commit is contained in:
1 parent
e829d665ca
commit
5128b25e88
33 files changed
+1096
-76
No files matched your search
@@ -0,0 +1,53 @@
|
||||
package httpchallenge
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Store) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
notFound := func() { w.WriteHeader(http.StatusNotFound) }
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
notFound()
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(r.URL.Path, PathPrefix) || r.URL.RawPath != "" || r.URL.RawQuery != "" {
|
||||
notFound()
|
||||
return
|
||||
}
|
||||
token := strings.TrimPrefix(r.URL.Path, PathPrefix)
|
||||
host := r.Host
|
||||
if strings.Contains(host, ":") {
|
||||
var port string
|
||||
var err error
|
||||
host, port, err = net.SplitHostPort(host)
|
||||
n, portErr := strconv.Atoi(port)
|
||||
if err != nil || portErr != nil || n < 1 || n > 65535 {
|
||||
notFound()
|
||||
return
|
||||
}
|
||||
}
|
||||
host, ok := normalizeHost(host)
|
||||
if s == nil || !ok || !validToken(token) {
|
||||
notFound()
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.prune(s.now())
|
||||
current, exists := s.entries[entryKey{host: host, token: token}]
|
||||
s.mu.Unlock()
|
||||
if !exists {
|
||||
notFound()
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(current.value)))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if r.Method == http.MethodGet {
|
||||
_, _ = w.Write([]byte(current.value))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package httpchallenge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
const PathPrefix = "/.well-known/acme-challenge/"
|
||||
|
||||
type entryKey struct {
|
||||
host string
|
||||
token string
|
||||
}
|
||||
|
||||
type entry struct {
|
||||
owner *Lease
|
||||
value string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// Store 仅在进程内保存短期挑战,不落盘、不跨订单共享挑战内容。
|
||||
type Store struct {
|
||||
mu sync.Mutex
|
||||
entries map[entryKey]entry
|
||||
ttl time.Duration
|
||||
capacity int
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewStore() *Store {
|
||||
return &Store{entries: make(map[entryKey]entry), ttl: 15 * time.Minute, capacity: 4096, now: time.Now}
|
||||
}
|
||||
|
||||
type Lease struct {
|
||||
store *Store
|
||||
hosts map[string]struct{}
|
||||
ctx context.Context
|
||||
closed bool
|
||||
stop func() bool
|
||||
}
|
||||
|
||||
func (s *Store) NewLease(ctx context.Context, names []string) (*Lease, error) {
|
||||
if s == nil || len(names) == 0 || len(names) > 100 {
|
||||
return nil, errors.New("HTTP 验证服务未初始化或域名数量无效")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := &Lease{store: s, ctx: ctx, hosts: make(map[string]struct{}, len(names))}
|
||||
for _, name := range names {
|
||||
host, ok := normalizeHost(name)
|
||||
if !ok {
|
||||
return nil, errors.New("HTTP 验证仅支持普通域名,不支持泛域名")
|
||||
}
|
||||
l.hosts[host] = struct{}{}
|
||||
}
|
||||
l.stop = context.AfterFunc(ctx, l.closeEntries)
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func normalizeHost(name string) (string, bool) {
|
||||
name = strings.ToLower(strings.TrimSuffix(name, "."))
|
||||
return name, len(name) <= 253 && !strings.HasPrefix(name, "*.") && domain.IsValidName(name) && strings.TrimSpace(name) == name
|
||||
}
|
||||
|
||||
func validToken(token string) bool {
|
||||
if len(token) < 22 || len(token) > 256 {
|
||||
return false
|
||||
}
|
||||
for _, c := range token {
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (l *Lease) Present(ctx context.Context, name, token, keyAuth string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
host, ok := normalizeHost(name)
|
||||
if !ok || !validToken(token) || !strings.HasPrefix(keyAuth, token+".") || !validToken(strings.TrimPrefix(keyAuth, token+".")) {
|
||||
return errors.New("HTTP 挑战参数无效")
|
||||
}
|
||||
if _, ok := l.hosts[host]; !ok {
|
||||
return errors.New("HTTP 挑战域名不属于当前订单")
|
||||
}
|
||||
s := l.store
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if l.closed || l.ctx.Err() != nil {
|
||||
return errors.New("HTTP 验证订单已关闭")
|
||||
}
|
||||
now := s.now()
|
||||
s.prune(now)
|
||||
key := entryKey{host: host, token: token}
|
||||
if existing, exists := s.entries[key]; exists {
|
||||
if existing.owner != l || existing.value != keyAuth {
|
||||
return errors.New("HTTP 挑战令牌已被其他验证占用")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(s.entries) >= s.capacity {
|
||||
return errors.New("HTTP 挑战容量已满,请稍后重试")
|
||||
}
|
||||
s.entries[key] = entry{owner: l, value: keyAuth, expires: now.Add(s.ttl)}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanUp 不受已取消上下文影响,且只清理当前订单拥有的挑战。
|
||||
func (l *Lease) CleanUp(_ context.Context, name, token, keyAuth string) error {
|
||||
host, _ := normalizeHost(name)
|
||||
s := l.store
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
key := entryKey{host: host, token: token}
|
||||
if current, exists := s.entries[key]; exists && current.owner == l && current.value == keyAuth {
|
||||
delete(s.entries, key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *Lease) Close() {
|
||||
if l.stop != nil {
|
||||
l.stop()
|
||||
}
|
||||
l.closeEntries()
|
||||
}
|
||||
|
||||
func (l *Lease) closeEntries() {
|
||||
s := l.store
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
l.closed = true
|
||||
for key, current := range s.entries {
|
||||
if current.owner == l {
|
||||
delete(s.entries, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prune 的调用者必须持有锁;过期或取消的挑战不能继续对外提供。
|
||||
func (s *Store) prune(now time.Time) {
|
||||
for key, current := range s.entries {
|
||||
if !now.Before(current.expires) || current.owner.ctx.Err() != nil {
|
||||
delete(s.entries, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package httpchallenge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testToken = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"
|
||||
const testAuth = testToken + ".abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"
|
||||
|
||||
func newTestLease(t *testing.T, s *Store, ctx context.Context, names ...string) *Lease {
|
||||
t.Helper()
|
||||
l, err := s.NewLease(ctx, names)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(l.Close)
|
||||
return l
|
||||
}
|
||||
|
||||
func requestChallenge(s *Store, method, host, path string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, "http://"+host+path, nil)
|
||||
r.Header.Set("X-Forwarded-Host", "a.example.com")
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestChallengeHostTokenAndMethodIsolation(t *testing.T) {
|
||||
s := NewStore()
|
||||
l := newTestLease(t, s, context.Background(), "a.example.com")
|
||||
if err := l.Present(context.Background(), "a.example.com", testToken, testAuth); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
method, host, path string
|
||||
status int
|
||||
}{
|
||||
{"GET", "a.example.com", PathPrefix + testToken, 200},
|
||||
{"HEAD", "A.EXAMPLE.COM:80", PathPrefix + testToken, 200},
|
||||
{"GET", "b.example.com", PathPrefix + testToken, 404},
|
||||
{"POST", "a.example.com", PathPrefix + testToken, 404},
|
||||
{"GET", "a.example.com", PathPrefix + testToken + "x", 404},
|
||||
{"GET", "a.example.com", PathPrefix + testToken + "/", 404},
|
||||
{"GET", "a.example.com", PathPrefix + testToken + "?x=1", 404},
|
||||
{"GET", "a.example.com", PathPrefix + "%61" + testToken[1:], 404},
|
||||
{"GET", "a.example.com", "/unrelated/" + testToken, 404},
|
||||
} {
|
||||
w := requestChallenge(s, tc.method, tc.host, tc.path)
|
||||
if w.Code != tc.status || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("挑战响应不正确:%+v,状态 %d", tc, w.Code)
|
||||
}
|
||||
if tc.status == 200 && tc.method == "GET" && w.Body.String() != testAuth {
|
||||
t.Fatal("挑战内容不匹配")
|
||||
}
|
||||
if (tc.status == 404 || tc.method == "HEAD") && w.Body.Len() != 0 {
|
||||
t.Fatal("拒绝响应或 HEAD 泄漏挑战内容")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeaseOwnershipCancellationAndExpiry(t *testing.T) {
|
||||
s := NewStore()
|
||||
now := time.Now()
|
||||
s.now = func() time.Time { return now }
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
first := newTestLease(t, s, ctx, "a.example.com")
|
||||
second := newTestLease(t, s, context.Background(), "a.example.com")
|
||||
if err := first.Present(ctx, "a.example.com", testToken, testAuth); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := second.Present(ctx, "a.example.com", testToken, testAuth); err == nil {
|
||||
t.Fatal("不同订单不应覆盖同一挑战")
|
||||
}
|
||||
_ = second.CleanUp(ctx, "a.example.com", testToken, testAuth)
|
||||
if w := requestChallenge(s, "GET", "a.example.com", PathPrefix+testToken); w.Code != 200 {
|
||||
t.Fatal("其他订单清理删除了当前挑战")
|
||||
}
|
||||
cancel()
|
||||
if w := requestChallenge(s, "GET", "a.example.com", PathPrefix+testToken); w.Code != 404 {
|
||||
t.Fatal("已取消的挑战仍可读取")
|
||||
}
|
||||
if err := second.Present(context.Background(), "a.example.com", testToken, testAuth); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = first.CleanUp(ctx, "a.example.com", testToken, testAuth)
|
||||
first.Close()
|
||||
if w := requestChallenge(s, "GET", "a.example.com", PathPrefix+testToken); w.Code != 200 {
|
||||
t.Fatal("迟到清理误删了新订单挑战")
|
||||
}
|
||||
now = now.Add(s.ttl)
|
||||
if w := requestChallenge(s, "GET", "a.example.com", PathPrefix+testToken); w.Code != 404 {
|
||||
t.Fatal("到期挑战仍可读取")
|
||||
}
|
||||
second.Close()
|
||||
if err := second.Present(context.Background(), "a.example.com", testToken, testAuth); err == nil {
|
||||
t.Fatal("关闭后不应重新创建挑战")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChallengeValidationAndCapacity(t *testing.T) {
|
||||
s := NewStore()
|
||||
s.capacity = 1
|
||||
l := newTestLease(t, s, context.Background(), "a.example.com", "b.example.com")
|
||||
for _, tc := range []struct{ host, token, auth string }{
|
||||
{"c.example.com", testToken, testAuth},
|
||||
{"*.a.example.com", testToken, testAuth},
|
||||
{"a.example.com", "../token", testAuth},
|
||||
{"a.example.com", testToken, "other.auth"},
|
||||
{"a.example.com", testToken, testAuth + "\n"},
|
||||
} {
|
||||
if err := l.Present(context.Background(), tc.host, tc.token, tc.auth); err == nil {
|
||||
t.Fatal("无效挑战未被拒绝")
|
||||
}
|
||||
}
|
||||
if _, err := s.NewLease(context.Background(), []string{"*.example.com"}); err == nil {
|
||||
t.Fatal("泛域名订单未被拒绝")
|
||||
}
|
||||
if err := l.Present(context.Background(), "a.example.com", testToken, testAuth); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := l.Present(context.Background(), "b.example.com", testToken, testAuth); err == nil {
|
||||
t.Fatal("容量限制未生效")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_ = l.CleanUp(ctx, "a.example.com", testToken, testAuth)
|
||||
if err := l.Present(context.Background(), "b.example.com", testToken, testAuth); err != nil {
|
||||
t.Fatal("取消上下文阻碍清理:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChallengeConcurrentOrders(t *testing.T) {
|
||||
s := NewStore()
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 64; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
l, err := s.NewLease(ctx, []string{"a.example.com"})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
defer l.Close()
|
||||
token := fmt.Sprintf("%s%d", testToken, i)
|
||||
auth := token + "." + strings.Repeat("a", 43)
|
||||
if err := l.Present(ctx, "a.example.com", token, auth); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if w := requestChallenge(s, "GET", "a.example.com", PathPrefix+token); w.Code != 200 {
|
||||
t.Error("并发订单内容丢失")
|
||||
}
|
||||
cancel()
|
||||
_ = l.CleanUp(ctx, "a.example.com", token, auth)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.entries) != 0 {
|
||||
t.Fatal("并发订单清理后仍有残留")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user