...

Source file src/cloud.google.com/go/auth/credentials/idtoken/cache_test.go

Documentation: cloud.google.com/go/auth/credentials/idtoken

     1  // Copyright 2023 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package idtoken
    16  
    17  import (
    18  	"net/http"
    19  	"sync"
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  type fakeClock struct {
    25  	mu sync.Mutex
    26  	t  time.Time
    27  }
    28  
    29  func (c *fakeClock) Now() time.Time {
    30  	c.mu.Lock()
    31  	defer c.mu.Unlock()
    32  	return c.t
    33  }
    34  
    35  func (c *fakeClock) Sleep(d time.Duration) {
    36  	c.mu.Lock()
    37  	defer c.mu.Unlock()
    38  	c.t = c.t.Add(d)
    39  }
    40  
    41  func TestCacheHit(t *testing.T) {
    42  	clock := &fakeClock{t: time.Now()}
    43  	fakeResp := &certResponse{
    44  		Keys: []jwk{
    45  			{
    46  				Kid: "123",
    47  			},
    48  		},
    49  	}
    50  	cache := newCachingClient(nil)
    51  	cache.clock = clock.Now
    52  
    53  	// Cache should be empty
    54  	cert, ok := cache.get(googleSACertsURL)
    55  	if ok || cert != nil {
    56  		t.Fatal("cache for SA certs should be empty")
    57  	}
    58  
    59  	// Add an item, but make it expire now
    60  	cache.set(googleSACertsURL, fakeResp, make(http.Header))
    61  	clock.Sleep(time.Nanosecond) // it expires when current time is > expiration, not >=
    62  	cert, ok = cache.get(googleSACertsURL)
    63  	if ok || cert != nil {
    64  		t.Fatal("cache for SA certs should be expired")
    65  	}
    66  
    67  	// Add an item that expires in 1 seconds
    68  	h := make(http.Header)
    69  	h.Set("age", "0")
    70  	h.Set("cache-control", "public, max-age=1, must-revalidate, no-transform")
    71  	cache.set(googleSACertsURL, fakeResp, h)
    72  	cert, ok = cache.get(googleSACertsURL)
    73  	if !ok || cert == nil || cert.Keys[0].Kid != "123" {
    74  		t.Fatal("cache for SA certs have a resp")
    75  	}
    76  	// Wait
    77  	clock.Sleep(2 * time.Second)
    78  	cert, ok = cache.get(googleSACertsURL)
    79  	if ok || cert != nil {
    80  		t.Fatal("cache for SA certs should be expired")
    81  	}
    82  }
    83  

View as plain text