keypairs/keyfetch/fetch_test.go

72 lines
1.8 KiB
Go
Raw Normal View History

2019-02-21 00:10:42 +00:00
package keyfetch
2019-02-08 01:26:45 +00:00
import (
"testing"
2019-02-20 19:26:37 +00:00
"time"
2019-02-20 19:59:22 +00:00
keypairs "github.com/big-squid/go-keypairs"
2019-02-21 00:10:42 +00:00
"github.com/big-squid/go-keypairs/keyfetch/uncached"
2019-02-08 01:26:45 +00:00
)
2019-02-19 23:50:46 +00:00
func TestCachesKey(t *testing.T) {
testCachesKey(t, "https://bigsquid.auth0.com/")
clear()
testCachesKey(t, "https://bigsquid.auth0.com")
}
2019-02-20 19:26:37 +00:00
func testCachesKey(t *testing.T, url string) {
2019-02-19 23:50:46 +00:00
// Raw fetch a key and get KID and Thumbprint
2019-02-21 00:10:42 +00:00
_, keys, err := uncached.OIDCJWKs(url)
2019-02-20 19:26:37 +00:00
if nil != err {
t.Fatal(url, err)
}
if 0 == len(keys) {
t.Fatal("Should discover 1 or more keys via", url)
}
2019-02-20 19:59:22 +00:00
var key keypairs.PublicKey
2019-02-20 19:26:37 +00:00
for i := range keys {
key = keys[i]
break
}
thumb := key.Thumbprint()
2019-02-19 23:50:46 +00:00
// Look in cache for each (and fail)
2019-02-21 00:10:42 +00:00
if pub := Get(thumb, ""); nil != pub {
2019-02-20 19:26:37 +00:00
t.Fatal("SANITY: Should not have any key cached by thumbprint")
}
2019-02-19 23:50:46 +00:00
// Get with caching
2019-02-21 00:10:42 +00:00
k2, err := OIDCJWK(thumb, url)
2019-02-20 19:26:37 +00:00
if nil != err {
t.Fatal("Error fetching and caching key:", err)
}
2019-02-19 23:50:46 +00:00
// Look in cache for each (and succeed)
2019-02-21 00:10:42 +00:00
if pub := Get(thumb, ""); nil == pub {
t.Fatal("key was not properly cached by thumbprint", thumb)
2019-02-20 19:26:37 +00:00
}
if "" != k2.KeyID() {
2019-02-21 00:10:42 +00:00
if pub := Get(k2.KeyID(), url); nil == pub {
t.Fatal("key was not properly cached by kid", k2.KeyID())
2019-02-20 19:26:37 +00:00
}
} else {
t.Log("Key did not have an explicit KeyID")
}
2019-02-19 23:50:46 +00:00
// Get again (should be sub-ms instant)
2019-02-20 19:26:37 +00:00
now := time.Now()
2019-02-21 00:10:42 +00:00
_, err = OIDCJWK(thumb, url)
2019-02-20 19:26:37 +00:00
if nil != err {
t.Fatal("SANITY: Failed to get the key we just got...", err)
}
if time.Now().Sub(now) > time.Millisecond {
t.Fatal("Failed to cache key by thumbprint...", time.Now().Sub(now))
}
// Sanity check that the kid and thumb match
if key.KeyID() != k2.KeyID() || key.Thumbprint() != k2.Thumbprint() {
t.Fatal("SANITY: KeyIDs or Thumbprints do not match:", key.KeyID(), k2.KeyID(), key.Thumbprint(), k2.Thumbprint())
}
2019-02-19 23:50:46 +00:00
}