File
Blob: spec/pki/token_test.go
| 1 | package pki |
| 2 | |
| 3 | import ( |
| 4 | "crypto/ed25519" |
| 5 | "crypto/rand" |
| 6 | "crypto/x509" |
| 7 | "crypto/x509/pkix" |
| 8 | "math/big" |
| 9 | "testing" |
| 10 | |
| 11 | "github.com/stretchr/testify/require" |
| 12 | ) |
| 13 | |
| 14 | func makeCert(as *require.Assertions, sub pkix.Name) *x509.Certificate { |
| 15 | cert := &x509.Certificate{ |
| 16 | SerialNumber: big.NewInt(1234), |
| 17 | Subject: sub, |
| 18 | } |
| 19 | |
| 20 | caPubKey, caPrivKey, err := ed25519.GenerateKey(rand.Reader) |
| 21 | as.NoError(err) |
| 22 | |
| 23 | certBytes, err := x509.CreateCertificate(rand.Reader, cert, cert, caPubKey, caPrivKey) |
| 24 | as.NoError(err) |
| 25 | |
| 26 | parsed, err := x509.ParseCertificate(certBytes) |
| 27 | as.NoError(err) |
| 28 | |
| 29 | return parsed |
| 30 | } |
| 31 | |
| 32 | func TestTokenV1(t *testing.T) { |
| 33 | as := require.New(t) |
| 34 | |
| 35 | var ( |
| 36 | id uint64 = 256 |
| 37 | token string = "token" |
| 38 | ) |
| 39 | |
| 40 | sub := MakeSubjectV1(id, token) |
| 41 | t.Log(sub) |
| 42 | identity, err := ExtractCertificateIdentity(makeCert(as, sub)) |
| 43 | as.NoError(err) |
| 44 | as.Contains(sub.CommonName, string(identity.Token)) |
| 45 | as.Equal(TokenV1, identity.Version) |
| 46 | as.Equal(id, identity.ID) |
| 47 | } |
| 48 | |
| 49 | func TestTokenV2(t *testing.T) { |
| 50 | as := require.New(t) |
| 51 | |
| 52 | var ( |
| 53 | id uint64 = 256 |
| 54 | hash []byte = []byte{1, 2, 3, 4, 5} |
| 55 | ) |
| 56 | |
| 57 | sub := MakeSubjectV2(id, hash) |
| 58 | t.Log(sub) |
| 59 | identity, err := ExtractCertificateIdentity(makeCert(as, sub)) |
| 60 | as.NoError(err) |
| 61 | as.Equal(sub.CommonName, string(identity.Token)) |
| 62 | as.Equal(TokenV2, identity.Version) |
| 63 | as.Equal(id, identity.ID) |
| 64 | } |
| 65 | |
| 66 | func TestNodeIdentity(t *testing.T) { |
| 67 | as := require.New(t) |
| 68 | |
| 69 | // Test that NodeIdentity produces expected protocol.Node for v1 |
| 70 | v1Identity := &Identity{ |
| 71 | ID: 12345, |
| 72 | Token: []byte("oldtoken"), |
| 73 | Version: TokenV1, |
| 74 | } |
| 75 | v1Node := v1Identity.NodeIdentity() |
| 76 | as.Equal(uint64(12345), v1Node.GetId()) |
| 77 | as.Equal("oldtoken", v1Node.GetAddress()) |
| 78 | as.True(v1Node.GetRendezvous()) |
| 79 | |
| 80 | // Test that NodeIdentity produces expected protocol.Node for v2 |
| 81 | // For v2, Token is the full CN |
| 82 | v2CN := "v2:67890:AQIDBAU=" |
| 83 | v2Identity := &Identity{ |
| 84 | ID: 67890, |
| 85 | Token: []byte(v2CN), |
| 86 | Version: TokenV2, |
| 87 | } |
| 88 | v2Node := v2Identity.NodeIdentity() |
| 89 | as.Equal(uint64(67890), v2Node.GetId()) |
| 90 | as.Equal(v2CN, v2Node.GetAddress()) |
| 91 | as.True(v2Node.GetRendezvous()) |
| 92 | } |