ezshare/certs/certservice_test.go
2021-12-05 01:01:05 +01:00

85 lines
2.1 KiB
Go

package certs_test
import (
"crypto/x509"
"encoding/pem"
"gitea.benny.dog/torjus/ezshare/certs"
"gitea.benny.dog/torjus/ezshare/store"
"github.com/google/uuid"
"testing"
)
func TestCertService(t *testing.T) {
t.Run("TestManualVerifyClientCertificate", func(t *testing.T) {
s := store.NewMemoryStore()
caKeyBytes, caCertBytes, err := certs.GenCACert()
if err != nil {
t.Fatalf("Error generating ca cert: %s", err)
}
svc, err := certs.NewCertService(s, caCertBytes, caKeyBytes)
if err != nil {
t.Fatalf("Unable to create service: %s", err)
}
clientCertPEM, _, err := svc.NewClient("test")
if err != nil {
t.Fatalf("Unable to create client certificate: %s", err)
}
caCert, err := x509.ParseCertificate(caCertBytes)
if err != nil {
t.Fatalf("Unable to parse CA certificate: %s", err)
}
certPool := x509.NewCertPool()
certPool.AddCert(caCert)
clientCertPEMBlock, _ := pem.Decode(clientCertPEM)
if clientCertPEMBlock == nil {
t.Fatalf("Client does not contain PEM-encoded data")
}
if clientCertPEMBlock.Type != "CERTIFICATE" {
t.Fatal("Client cert is not certificate")
}
clientCert, err := x509.ParseCertificate(clientCertPEMBlock.Bytes)
if err != nil {
t.Fatalf("Could not parse client certificate: %s", err)
}
if _, err := clientCert.Verify(x509.VerifyOptions{Roots: certPool}); err != nil {
t.Fatalf("Could not verify client certificate: %s", err)
}
})
t.Run("TestVerifyClientCertificate", func(t *testing.T) {
s := store.NewMemoryStore()
caKeyBytes, caCertBytes, err := certs.GenCACert()
if err != nil {
t.Fatalf("Error generating ca cert: %s", err)
}
svc, err := certs.NewCertService(s, caCertBytes, caKeyBytes)
if err != nil {
t.Fatalf("Unable to create service: %s", err)
}
clientID := uuid.Must(uuid.NewRandom()).String()
clientCertPEM, _, err := svc.NewClient(clientID)
if err != nil {
t.Fatalf("Unable to create client certificate: %s", err)
}
id, err := svc.VerifyClient(clientCertPEM)
if err != nil {
t.Fatalf("Failed to verify certificate: %s", err)
}
if id != clientID {
t.Fatalf("Verify returned wrong id. Got %s want %s", id, clientID)
}
})
}