package security import ( "context" "testing" "time" jwt "github.com/golang-jwt/jwt/v5" "google.golang.org/grpc/metadata" ) func benchmarkFilerAuthConnRequestContext(b *testing.B, source FilerTokenSource, wantToken bool) { c := &filerAuthConn{source: source} ctx, err := c.requestContext(context.Background(), "/filer_pb.SeaweedFiler/CreateEntry") if err != nil { b.Fatal(err) } if got := metadata.ValueFromOutgoingContext(ctx, "authorization") != nil; got != wantToken { b.Fatalf("authorization set %v, want %v", got, wantToken) } b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if _, err := c.requestContext(context.Background(), "/filer_pb.SeaweedFiler/CreateEntry"); err != nil { b.Fatal(err) } } }) } func BenchmarkFilerAuthConnRequestContext(b *testing.B) { key := SigningKey("0123456789abcdef0123456789abcdef") benchmarkFilerAuthConnRequestContext(b, func(context.Context) (EncodedJwt, error) { return GenJwtForFilerAdmin(key, 10), nil }, true) } func BenchmarkFilerAuthConnRequestContextTokenless(b *testing.B) { benchmarkFilerAuthConnRequestContext(b, func(context.Context) (EncodedJwt, error) { return GenJwtForFilerAdmin(nil, 10), nil }, false) } // withinOneSecond runs f until a run starts and ends in the same second. func withinOneSecond(f func(start int64)) { for { start := time.Now().Unix() f(start) if time.Now().Unix() == start { return } } } func TestGenJwtForFilerAdminReusesSameSecondToken(t *testing.T) { key := SigningKey("0123456789abcdef0123456789abcdef") var first, second EncodedJwt var cachedBefore, cachedAfter *filerAdminJwt withinOneSecond(func(int64) { first = GenJwtForFilerAdmin(key, 10) cachedBefore = lastFilerAdminJwt.Load() second = GenJwtForFilerAdmin(key, 10) cachedAfter = lastFilerAdminJwt.Load() }) if first == "" || first != second { t.Fatalf("tokens signed in one second differ: %q %q", first, second) } if cachedBefore != cachedAfter { t.Fatal("the second token was signed again instead of reused") } } func TestGenJwtForFilerAdminKeepsKeysApart(t *testing.T) { keyA := SigningKey("0123456789abcdef0123456789abcdef") keyB := SigningKey("fedcba9876543210fedcba9876543210") var a1, b1, a2 EncodedJwt var start int64 withinOneSecond(func(s int64) { start = s a1 = GenJwtForFilerAdmin(keyA, 10) b1 = GenJwtForFilerAdmin(keyB, 10) a2 = GenJwtForFilerAdmin(keyA, 10) }) if a1 != a2 || a1 == b1 { t.Fatalf("tokens per key: a1=%q b=%q a2=%q", a1, b1, a2) } for key, token := range map[string]EncodedJwt{string(keyA): a2, string(keyB): b1} { claims := &SeaweedFilerAdminClaims{} parsed, err := jwt.ParseWithClaims(string(token), claims, func(*jwt.Token) (interface{}, error) { return []byte(key), nil }) if err != nil || !parsed.Valid { t.Fatalf("token does not verify with its key: %v", err) } if got := claims.ExpiresAt.Unix(); got < start+9 || got > start+11 { t.Fatalf("expiry %d, want about %d", got, start+10) } } }