github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/pki/ssh/format_test.go (about)

     1  // Copyright 2022 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package ssh_test
     5  
     6  import (
     7  	"crypto/ecdsa"
     8  	"crypto/elliptic"
     9  	"crypto/rand"
    10  
    11  	jc "github.com/juju/testing/checkers"
    12  	cryptossh "golang.org/x/crypto/ssh"
    13  	gc "gopkg.in/check.v1"
    14  
    15  	"github.com/juju/juju/pki/ssh"
    16  )
    17  
    18  type FormatSuite struct {
    19  }
    20  
    21  var _ = gc.Suite(&FormatSuite{})
    22  
    23  func (s *FormatSuite) TestKeyProfilesFormat(c *gc.C) {
    24  	tests := []struct {
    25  		name          string
    26  		profile       ssh.KeyProfile
    27  		publicKeyType string
    28  	}{
    29  		{name: "ecdsa256", profile: ssh.ECDSAP256, publicKeyType: cryptossh.KeyAlgoECDSA256},
    30  		{name: "ecdsa384", profile: ssh.ECDSAP384, publicKeyType: cryptossh.KeyAlgoECDSA384},
    31  		{name: "ecdsa521", profile: ssh.ECDSAP521, publicKeyType: cryptossh.KeyAlgoECDSA521},
    32  		{name: "rsa2048", profile: ssh.RSA2048, publicKeyType: cryptossh.KeyAlgoRSA},
    33  		{name: "rsa3072", profile: ssh.RSA3072, publicKeyType: cryptossh.KeyAlgoRSA},
    34  		{name: "ed25519", profile: ssh.ED25519, publicKeyType: cryptossh.KeyAlgoED25519},
    35  	}
    36  	for _, test := range tests {
    37  		pk, err := test.profile()
    38  		c.Check(err, jc.ErrorIsNil, gc.Commentf("profile %s", test.name))
    39  
    40  		private, public, publicKeyType, err := ssh.FormatKey(pk, "test-comment")
    41  		c.Check(err, jc.ErrorIsNil, gc.Commentf("profile %s", test.name))
    42  		c.Check(private, gc.Not(gc.Equals), "")
    43  		c.Check(public, gc.Not(gc.Equals), "")
    44  		c.Check(public, gc.Matches, test.publicKeyType+` .* test-comment\n`)
    45  		c.Check(publicKeyType, gc.Equals, test.publicKeyType)
    46  	}
    47  }
    48  
    49  func (s *FormatSuite) TestBadKey(c *gc.C) {
    50  	_, _, _, err := ssh.FormatKey(nil, "nope")
    51  	c.Assert(err, gc.ErrorMatches, `private key not valid`)
    52  	_, _, _, err = ssh.FormatKey(&struct{}{}, "nope")
    53  	c.Assert(err, gc.ErrorMatches, `private key not valid`)
    54  	_, _, _, err = ssh.FormatKey(&ecdsa.PrivateKey{}, "nope")
    55  	c.Assert(err, gc.ErrorMatches, `cannot encode private key: x509: unknown curve while marshaling to PKCS#8`)
    56  
    57  	pk, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
    58  	c.Assert(err, jc.ErrorIsNil)
    59  	_, _, _, err = ssh.FormatKey(pk, "nope")
    60  	c.Assert(err, gc.ErrorMatches, `cannot encode public key: public key: ssh: only P-256, P-384 and P-521 EC keys are supported`)
    61  }