Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

6.6 KB
Raw Blame
// SiYuan - https://github.com/siyuan-note/siyuan
// Copyright (c) 2020-present, b3log.org
// SPDX-License-Identifier: AGPL-3.0-or-later

package util

import (
	"fmt"
	"testing"
	"time"
)

// TestAuthCodeEquals 验证恒定时间比较的相等与不等判定。
func TestAuthCodeEquals(t *testing.T) {
	if !AuthCodeEquals("secret123", "secret123") {
		t.Fatal("equal codes should match")
	}
	if AuthCodeEquals("secret123", "secret124") {
		t.Fatal("different codes should not match")
	}
	if AuthCodeEquals("secret123", "secret") {
		t.Fatal("codes of different length should not match")
	}
	if AuthCodeEquals("", "secret123") || AuthCodeEquals("secret123", "") {
		t.Fatal("empty code should not match a non-empty one")
	}
	if !AuthCodeEquals("", "") {
		t.Fatal("both empty codes should match")
	}
}

// TestAuthThrottleThreshold 验证未达阈值不锁定、超过阈值后锁定。
func TestAuthThrottleThreshold(t *testing.T) {
	key := "TestAuthThrottleThreshold"
	resetAuthThrottleForTest(key)
	for i := range authThrottleMaxFail {
		if retryAfter := AuthThrottleCheck(key); 0 < retryAfter {
			t.Fatalf("locked before reaching threshold at attempt %d", i+1)
		}
		AuthThrottleFail(key)
	}
	AuthThrottleFail(key)
	if retryAfter := AuthThrottleCheck(key); 0 >= retryAfter {
		t.Fatal("expected lock after exceeding threshold")
	}
}

// TestAuthThrottleBackoff 验证锁定期随持续失败指数增长且不超过上限。
func TestAuthThrottleBackoff(t *testing.T) {
	key := "TestAuthThrottleBackoff"
	resetAuthThrottleForTest(key)
	for range authThrottleMaxFail + 1 {
		AuthThrottleFail(key)
	}
	firstLock := time.Until(authThrottles[key].LockUntil)
	for range authThrottleMaxFail {
		AuthThrottleFail(key)
	}
	extendedLock := time.Until(authThrottles[key].LockUntil)
	if !(extendedLock > firstLock) {
		t.Fatal("expected lock to extend while failures keep coming")
	}
	if authThrottleLockMaxSec*time.Second < extendedLock {
		t.Fatalf("lock exceeded the cap: %v", extendedLock)
	}
}

func TestAuthThrottleSaturation(t *testing.T) {
	key := "TestAuthThrottleSaturation"
	resetAuthThrottleForTest(key)
	t.Cleanup(func() { resetAuthThrottleForTest(key) })
	for i := 1; i <= 1000; i++ {
		AuthThrottleFail(key)
		if i < 10 {
			continue
		}
		if retryAfter := AuthThrottleCheck(key); retryAfter < authThrottleLockMaxSec || retryAfter > authThrottleLockMaxSec+1 {
			t.Fatalf("lock lost its cap after %d failures: %d", i, retryAfter)
		}
	}
	authThrottleLock.Lock()
	count := authThrottles[key].FailCount
	authThrottleLock.Unlock()
	if count > 10 {
		t.Fatalf("failure count was not saturated: %d", count)
	}
}

// TestAuthThrottleWindowReset 验证窗口期外的陈旧失败计数被清零,避免误锁。
func TestAuthThrottleWindowReset(t *testing.T) {
	key := "TestAuthThrottleWindowReset"
	resetAuthThrottleForTest(key)
	AuthThrottleFail(key)
	authThrottleLock.Lock()
	authThrottles[key].LastFail = time.Now().Add(-authThrottleWindowSec * time.Second)
	authThrottleLock.Unlock()
	AuthThrottleFail(key)
	authThrottleLock.Lock()
	count := authThrottles[key].FailCount
	authThrottleLock.Unlock()
	if count != 1 {
		t.Fatalf("expected stale failure count to reset, got %d", count)
	}
}

// TestAuthThrottleReset 验证认证成功后清除失败计数。
func TestAuthThrottleReset(t *testing.T) {
	key := "TestAuthThrottleReset"
	resetAuthThrottleForTest(key)
	for range authThrottleMaxFail + 1 {
		AuthThrottleFail(key)
	}
	if retryAfter := AuthThrottleCheck(key); 0 >= retryAfter {
		t.Fatal("expected lock before reset")
	}
	AuthThrottleReset(key)
	if retryAfter := AuthThrottleCheck(key); 0 < retryAfter {
		t.Fatal("expected no lock after reset")
	}
}

// TestAuthThrottleExpiry 验证锁定期过期后解除锁定并清理记录。
func TestAuthThrottleExpiry(t *testing.T) {
	key := "TestAuthThrottleExpiry"
	resetAuthThrottleForTest(key)
	for range authThrottleMaxFail + 1 {
		AuthThrottleFail(key)
	}
	authThrottleLock.Lock()
	authThrottles[key].LockUntil = time.Now().Add(-time.Second)
	authThrottleLock.Unlock()
	if retryAfter := AuthThrottleCheck(key); 0 < retryAfter {
		t.Fatal("expected lock to be expired")
	}
	authThrottleLock.Lock()
	_, exists := authThrottles[key]
	authThrottleLock.Unlock()
	if exists {
		t.Fatal("expected expired throttle entry to be cleaned up")
	}
}

// TestAuthThrottleSweep 验证定期清扫会删除窗口期已过的失败记录,即使 key 不再被访问。
func TestAuthThrottleSweep(t *testing.T) {
	staleKeys := make([]string, 0, 64)
	for i := range 64 {
		key := fmt.Sprintf("TestAuthThrottleSweep-stale-%d", i)
		AuthThrottleFail(key)
		defer resetAuthThrottleForTest(key)
		staleKeys = append(staleKeys, key)
	}
	authThrottleLock.Lock()
	for _, key := range staleKeys {
		authThrottles[key].LastFail = time.Now().Add(-authThrottleWindowSec * time.Second)
	}
	authThrottleLastSweep = time.Time{}
	authThrottleLock.Unlock()

	triggerKey := "TestAuthThrottleSweep-trigger"
	defer resetAuthThrottleForTest(triggerKey)
	AuthThrottleFail(triggerKey)

	authThrottleLock.Lock()
	defer authThrottleLock.Unlock()
	for _, key := range staleKeys {
		if _, exists := authThrottles[key]; exists {
			t.Fatalf("expected stale throttle entry to be swept: %s", key)
		}
	}
}

// TestAuthThrottleSweepKeepsLocked 验证清扫不会删除仍在锁定中的条目。
func TestAuthThrottleSweepKeepsLocked(t *testing.T) {
	key := "TestAuthThrottleSweepKeepsLocked"
	resetAuthThrottleForTest(key)
	defer resetAuthThrottleForTest(key)
	for range authThrottleMaxFail + 1 {
		AuthThrottleFail(key)
	}
	authThrottleLock.Lock()
	authThrottleLastSweep = time.Time{}
	authThrottleLock.Unlock()

	triggerKey := "TestAuthThrottleSweepKeepsLocked-trigger"
	defer resetAuthThrottleForTest(triggerKey)
	AuthThrottleFail(triggerKey)

	authThrottleLock.Lock()
	defer authThrottleLock.Unlock()
	if _, exists := authThrottles[key]; !exists {
		t.Fatal("expected locked throttle entry to survive sweep")
	}
}

// TestAuthThrottleMaxEntries 验证限流记录条数不超过上限,防止唯一 key 无限增长内存。
func TestAuthThrottleMaxEntries(t *testing.T) {
	authThrottleLock.Lock()
	authThrottleLastSweep = time.Now()
	for key := range authThrottles {
		delete(authThrottles, key)
	}
	authThrottleLock.Unlock()

	for i := range authThrottleMaxEntries + 50 {
		AuthThrottleFail(fmt.Sprintf("TestAuthThrottleMaxEntries-%d", i))
	}
	authThrottleLock.Lock()
	count := len(authThrottles)
	for key := range authThrottles {
		delete(authThrottles, key)
	}
	authThrottleLock.Unlock()
	if authThrottleMaxEntries < count {
		t.Fatalf("throttle entries exceeded the cap: %d", count)
	}
}

func resetAuthThrottleForTest(key string) {
	authThrottleLock.Lock()
	delete(authThrottles, key)
	authThrottleLock.Unlock()
}