clavitor/clavis/clavis-vault/api/middleware_test.go

70 lines
2.0 KiB
Go

package api
import (
"testing"
)
func TestAgentLimiter_RepeatedSameEntryDoesNotCount(t *testing.T) {
al := newAgentLimiter()
// Limit: 2 unique per minute. Same entry fetched 10 times = 1 unique.
for i := 0; i < 10; i++ {
if !al.allowEntry("agent-A", "entry-1", 2, 0) {
t.Fatalf("repeated read of entry-1 should be allowed (iter %d)", i)
}
}
}
func TestAgentLimiter_DistinctEntriesCountTowardLimit(t *testing.T) {
al := newAgentLimiter()
if !al.allowEntry("agent-A", "entry-1", 2, 0) {
t.Fatal("entry-1 should be allowed")
}
if !al.allowEntry("agent-A", "entry-2", 2, 0) {
t.Fatal("entry-2 should be allowed")
}
if al.allowEntry("agent-A", "entry-3", 2, 0) {
t.Error("entry-3 should be blocked (3 unique > limit of 2)")
}
// Re-fetching one of the existing entries should still work — it's not new.
if !al.allowEntry("agent-A", "entry-1", 2, 0) {
t.Error("re-fetching entry-1 should still be allowed")
}
}
func TestAgentLimiter_PerAgentIsolation(t *testing.T) {
al := newAgentLimiter()
// Saturate agent A.
al.allowEntry("agent-A", "e1", 1, 0)
if al.allowEntry("agent-A", "e2", 1, 0) {
t.Error("agent-A second unique entry should be blocked")
}
// Agent B is unaffected.
if !al.allowEntry("agent-B", "e1", 1, 0) {
t.Error("agent-B should be unaffected by agent-A's quota")
}
}
func TestAgentLimiter_HourLimitIndependent(t *testing.T) {
al := newAgentLimiter()
// Minute unlimited, hour = 2.
if !al.allowEntry("agent-A", "e1", 0, 2) {
t.Fatal("e1 within hour limit should be allowed")
}
if !al.allowEntry("agent-A", "e2", 0, 2) {
t.Fatal("e2 within hour limit should be allowed")
}
if al.allowEntry("agent-A", "e3", 0, 2) {
t.Error("e3 should be blocked by hour limit")
}
}
func TestAgentLimiter_ZeroLimitsMeanUnlimited(t *testing.T) {
al := newAgentLimiter()
for i := 0; i < 100; i++ {
entryID := "entry-" + string(rune('a'+i%26))
if !al.allowEntry("agent-A", entryID, 0, 0) {
t.Fatalf("zero limits = unlimited; iter %d unexpectedly blocked", i)
}
}
}