Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

agent: fix JWT cache #4309

Merged
merged 2 commits into from
Jun 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pkg/agent/manager/cache/jwt_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,19 @@ func (c *JWTSVIDCache) SetJWTSVID(spiffeID spiffeid.ID, audience []string, svid
func jwtSVIDKey(spiffeID spiffeid.ID, audience []string) string {
h := sha256.New()

// Form the cache key as the SHA-256 hash of the SPIFFE ID and all the audiences.
// In order to avoid ambiguities, we will write a nul byte to the hash function after each data
// item.

// duplicate and sort the audience slice
audience = append([]string(nil), audience...)
sort.Strings(audience)

_, _ = io.WriteString(h, spiffeID.String())
h.Write([]byte{0})
for _, a := range audience {
_, _ = io.WriteString(h, a)
h.Write([]byte{0})
}

return base64.StdEncoding.EncodeToString(h.Sum(nil))
Expand Down
22 changes: 21 additions & 1 deletion pkg/agent/manager/cache/jwt_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestJWTSVIDCache(t *testing.T) {
func TestJWTSVIDCacheBasic(t *testing.T) {
now := time.Now()
expected := &client.JWTSVID{Token: "X", IssuedAt: now, ExpiresAt: now.Add(time.Second)}

Expand All @@ -28,3 +28,23 @@ func TestJWTSVIDCache(t *testing.T) {
assert.True(t, ok)
assert.Equal(t, expected, actual)
}

func TestJWTSVIDCacheKeyHashing(t *testing.T) {
spiffeID := spiffeid.RequireFromString("spiffe://example.org/blog")
now := time.Now()
expected := &client.JWTSVID{Token: "X", IssuedAt: now, ExpiresAt: now.Add(time.Second)}

cache := NewJWTSVIDCache()
cache.SetJWTSVID(spiffeID, []string{"ab", "cd"}, expected)

// JWT is cached
actual, ok := cache.GetJWTSVID(spiffeID, []string{"ab", "cd"})
assert.True(t, ok)
assert.Equal(t, expected, actual)

// JWT is not cached, despite concatenation of audiences (in lexicographical order) matching
// that of the cached item
actual, ok = cache.GetJWTSVID(spiffeID, []string{"a", "bcd"})
assert.False(t, ok)
assert.Nil(t, actual)
}