package store import ( "crypto/sha256" "strings" "testing" ) func TestMintedKeysAreUniqueAndWellFormed(t *testing.T) { seen := map[string]struct{}{} for range 200 { secret, k, err := NewKey("id", "name", "proj") if err != nil { t.Fatal(err) } if _, dup := seen[secret]; dup { t.Fatal("two keys came out identical") } seen[secret] = struct{}{} if err := ParseKey(secret); err != nil { t.Fatalf("a minted key does not parse: %v (%q)", err, secret) } // Fixed width, so a key's length says nothing about its value and // listings line up. if len(secret) != len(KeyPrefix)+43 { t.Fatalf("length %d: %q", len(secret), secret) } sum := sha256.Sum256([]byte(secret)) if string(k.Hash) != string(sum[:]) { t.Fatal("the stored hash is not the hash of the key") } } } func TestParseRejectsWhatCannotBeAKey(t *testing.T) { // Cheap rejection, so a bearer token from another system never reaches the // database at all. for _, bad := range []string{ "", "hello", "Bearer abc", "sk-llmgw-", "sk-llmgw-short", "sk-proj-0123456789012345678901234567890123456789012", "sk-llmgw-0123456789012345678901234567890123456789+/=", } { if err := ParseKey(bad); err == nil { t.Errorf("%q was accepted as a key", bad) } } } func TestDisplayPrefixRevealsAlmostNothing(t *testing.T) { secret, k, _ := NewKey("id", "name", "proj") if !strings.HasPrefix(secret, k.Prefix[:len(KeyPrefix)+4]) { t.Errorf("prefix %q does not belong to %q", k.Prefix, secret) } // Four characters of base62 is enough to tell keys apart in a listing and // about 15 million times too few to guess the rest. body := strings.TrimSuffix(strings.TrimPrefix(k.Prefix, KeyPrefix), "…") if len(body) != 4 { t.Errorf("the display prefix shows %d characters", len(body)) } } func TestEqualHashIsUsable(t *testing.T) { a := HashKey("sk-llmgw-aaa") b := HashKey("sk-llmgw-aaa") c := HashKey("sk-llmgw-bbb") if !EqualHash(a, b) { t.Error("equal hashes compared unequal") } if EqualHash(a, c) { t.Error("different hashes compared equal") } if EqualHash(a, c[:16]) { t.Error("a truncated hash compared equal") } }