collateral_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package collateral
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "sync/atomic"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. )
  12. func TestGetter(t *testing.T) {
  13. var hits atomic.Int32
  14. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. hits.Add(1)
  16. if r.URL.Path == "/missing" {
  17. http.NotFound(w, r)
  18. return
  19. }
  20. w.Header().Set("TCB-Info-Issuer-Chain", "chain")
  21. _, _ = w.Write([]byte("collateral"))
  22. }))
  23. t.Cleanup(srv.Close)
  24. now := time.Now()
  25. g := New(srv.Client())
  26. g.now = func() time.Time { return now }
  27. tdx := TDX{g}
  28. sev := SEVSNP{g}
  29. header, body, err := tdx.Get(srv.URL + "/tcb")
  30. require.NoError(t, err)
  31. assert.Equal(t, []byte("collateral"), body)
  32. assert.Equal(t, []string{"chain"}, header["Tcb-Info-Issuer-Chain"])
  33. // A cached response is served without a request, to either library.
  34. body, err = sev.GetContext(context.Background(), srv.URL+"/tcb")
  35. require.NoError(t, err)
  36. assert.Equal(t, []byte("collateral"), body)
  37. assert.Equal(t, int32(1), hits.Load())
  38. // After the TTL it is fetched again.
  39. now = now.Add(TTL + time.Second)
  40. _, err = sev.Get(srv.URL + "/tcb")
  41. require.NoError(t, err)
  42. assert.Equal(t, int32(2), hits.Load())
  43. // Failures are not cached.
  44. for range 2 {
  45. _, _, err = tdx.GetContext(context.Background(), srv.URL+"/missing")
  46. assert.ErrorContains(t, err, "status code 404")
  47. }
  48. assert.Equal(t, int32(4), hits.Load())
  49. }