package admin import ( "context" "testing" "time" "github.com/alicebob/miniredis/v2" "github.com/redis/go-redis/v9" ) func newTestTrustedStore(t *testing.T) (*TrustedStore, *miniredis.Miniredis) { t.Helper() mr, err := miniredis.Run() if err != nil { t.Fatalf("miniredis: %v", err) } t.Cleanup(mr.Close) rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) return NewTrustedStore(rdb, 30*24*time.Hour), mr } func TestTrustedStore_IssueThenCheck(t *testing.T) { ts, _ := newTestTrustedStore(t) ctx := context.Background() tok, err := ts.Issue(ctx, 7) if err != nil { t.Fatalf("Issue: %v", err) } if tok == "" { t.Fatal("Issue returned empty token") } // 正确 admin 命中 if !ts.Check(ctx, tok, 7) { t.Error("Check should accept the token for the issuing admin") } // 令牌绑定 admin:换个 admin id 不认 if ts.Check(ctx, tok, 8) { t.Error("Check must reject a token bound to a different admin") } // 未知令牌不认 if ts.Check(ctx, "bogus-token", 7) { t.Error("Check must reject an unknown token") } // 空令牌不认 if ts.Check(ctx, "", 7) { t.Error("Check must reject an empty token") } } func TestTrustedStore_Revoke(t *testing.T) { ts, _ := newTestTrustedStore(t) ctx := context.Background() tok, _ := ts.Issue(ctx, 7) if !ts.Check(ctx, tok, 7) { t.Fatal("precondition: token should be valid") } if err := ts.Revoke(ctx, tok); err != nil { t.Fatalf("Revoke: %v", err) } if ts.Check(ctx, tok, 7) { t.Error("Check must reject a revoked token") } } func TestTrustedStore_Expires(t *testing.T) { mr, err := miniredis.Run() if err != nil { t.Fatalf("miniredis: %v", err) } defer mr.Close() rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) ts := NewTrustedStore(rdb, time.Hour) ctx := context.Background() tok, _ := ts.Issue(ctx, 7) if !ts.Check(ctx, tok, 7) { t.Fatal("precondition: token valid before expiry") } mr.FastForward(2 * time.Hour) // 超过 TTL if ts.Check(ctx, tok, 7) { t.Error("Check must reject an expired token (fail-closed)") } } // TTL<=0 视为功能关闭:Issue 返回空、Check 恒 false。 func TestTrustedStore_Disabled(t *testing.T) { mr, err := miniredis.Run() if err != nil { t.Fatalf("miniredis: %v", err) } defer mr.Close() rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) ts := NewTrustedStore(rdb, 0) ctx := context.Background() tok, err := ts.Issue(ctx, 7) if err != nil { t.Fatalf("Issue: %v", err) } if tok != "" { t.Error("disabled store should issue empty token") } if ts.Check(ctx, "anything", 7) { t.Error("disabled store should never trust") } }