cert.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Package sshtest provides helpers for creating SSH certificates in tests.
  2. package sshtest
  3. import (
  4. "crypto/rand"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/require"
  8. "golang.org/x/crypto/ssh"
  9. "go.step.sm/crypto/jose"
  10. "github.com/smallstep/certificates/internal/cast"
  11. )
  12. // CreateCertificate signs cert with signer and returns it together with the
  13. // JWK holding the private key for the certificate's public key.
  14. func CreateCertificate(t testing.TB, cert *ssh.Certificate, signer ssh.Signer) (*ssh.Certificate, *jose.JSONWebKey) {
  15. t.Helper()
  16. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "foo", 0)
  17. require.NoError(t, err)
  18. cert.Key, err = ssh.NewPublicKey(jwk.Public().Key)
  19. require.NoError(t, err)
  20. now := time.Now()
  21. if cert.ValidAfter == 0 {
  22. cert.ValidAfter = cast.Uint64(now.Unix())
  23. }
  24. if cert.ValidBefore == 0 {
  25. cert.ValidBefore = cast.Uint64(now.Add(time.Hour).Unix())
  26. }
  27. if len(cert.ValidPrincipals) == 0 {
  28. // set default principals; cert.SignCert fails without one set
  29. cert.ValidPrincipals = []string{"dummy.smallstep.com"}
  30. }
  31. require.NoError(t, cert.SignCert(rand.Reader, signer))
  32. return cert, jwk
  33. }