package idear import "testing" // TestNewToken_Distinct checks that two calls don't hand back the same // value — the one property that matters most for a credential, and the // cheapest way to catch a broken or unseeded random source. func TestNewToken_Distinct(t *testing.T) { a, err := newToken() if err != nil { t.Fatalf("newToken() error = %v", err) } b, err := newToken() if err != nil { t.Fatalf("newToken() error = %v", err) } if a == b { t.Fatalf("newToken() returned the same value twice: %q", a) } } // TestNewToken_Shape checks the encoding: 32 bytes of crypto/rand, // hex-encoded, is 64 hex characters. func TestNewToken_Shape(t *testing.T) { tok, err := newToken() if err != nil { t.Fatalf("newToken() error = %v", err) } if len(tok) != 64 { t.Fatalf("newToken() length = %d, want 64", len(tok)) } for _, c := range tok { if !isLowerHex(c) { t.Fatalf("newToken() = %q, contains non-lowercase-hex character %q", tok, c) } } } // TestHashToken_Stable checks that hashing the same token twice gives // the same digest — hashToken must be a pure function of its input. func TestHashToken_Stable(t *testing.T) { tok, err := newToken() if err != nil { t.Fatalf("newToken() error = %v", err) } if hashToken(tok) != hashToken(tok) { t.Fatalf("hashToken(%q) is not stable across calls", tok) } } // TestHashToken_Shape checks the encoding: SHA-256, hex-encoded, is 64 // hex characters, lowercase. func TestHashToken_Shape(t *testing.T) { tok, err := newToken() if err != nil { t.Fatalf("newToken() error = %v", err) } h := hashToken(tok) if len(h) != 64 { t.Fatalf("hashToken(%q) length = %d, want 64", tok, len(h)) } for _, c := range h { if !isLowerHex(c) { t.Fatalf("hashToken(%q) = %q, contains non-lowercase-hex character %q", tok, h, c) } } } // TestHashToken_DiffersFromInput checks that the hash is not just an // echo of the token — a bug that would defeat the entire point of // storing only the hash. func TestHashToken_DiffersFromInput(t *testing.T) { tok, err := newToken() if err != nil { t.Fatalf("newToken() error = %v", err) } if hashToken(tok) == tok { t.Fatalf("hashToken(%q) == input token; hash must differ from its input", tok) } } func isLowerHex(c rune) bool { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') }