| 1 | package certificate |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "net" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/smallstep/assert" |
| 10 | ) |
| 11 | |
| 12 | func TestTrimURL(t *testing.T) { |
| 13 | type newTest struct { |
| 14 | input, host string |
| 15 | isURL bool |
| 16 | err error |
| 17 | } |
| 18 | tests := map[string]newTest{ |
| 19 | "true-http": {"https://smallstep.com", "smallstep.com", true, nil}, |
| 20 | "true-tcp": {"tcp://smallstep.com:8080", "smallstep.com:8080", true, nil}, |
| 21 | "true-tls": {"tls://smallstep.com/onboarding", "smallstep.com", true, nil}, |
| 22 | "false": {"./certs/root_ca.crt", "", false, nil}, |
| 23 | "false-err": {"https://google.com hello", "", false, errors.New("error parsing URL 'https://google.com hello'")}, |
| 24 | "true-http-case": {"hTtPs://sMaLlStEp.cOm", "sMaLlStEp.cOm", true, nil}, |
| 25 | } |
| 26 | |
| 27 | for name, tc := range tests { |
| 28 | t.Run(name, func(t *testing.T) { |
| 29 | host, isURL, err := trimURL(tc.input) |
| 30 | assert.Equals(t, tc.host, host) |
| 31 | assert.Equals(t, tc.isURL, isURL) |
| 32 | if err != nil { |
| 33 | if assert.NotNil(t, tc.err) { |
| 34 | assert.HasPrefix(t, err.Error(), tc.err.Error()) |
| 35 | } |
| 36 | } else { |
| 37 | assert.Nil(t, tc.err) |
| 38 | } |
| 39 | }) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func TestGetPeerCertificateServerName(t *testing.T) { |
| 44 | host := "smallstep.com" |
| 45 | serverName := host |
| 46 | ips, err := net.LookupIP(host) |
| 47 | if err != nil { |
| 48 | t.Fatalf("unknown host %s: %s", host, err) |
| 49 | } |
| 50 | var addr string |
| 51 | for i, ip := range ips { |
| 52 | if ip.To4() != nil { |
| 53 | addr = ips[i].String() |
| 54 | break |
| 55 | } |
| 56 | } |
| 57 | if len(addr) == 0 { |
| 58 | assert.FatalError(t, errors.New("could not find ipv4 address for smallstep.com")) |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | type newTest struct { |
| 63 | addr, serverName string |
| 64 | err error |
| 65 | } |
| 66 | tests := map[string]newTest{ |
| 67 | "sni-disabled-host": {host, "", nil}, |
| 68 | "sni-enabled-host": {host, serverName, nil}, |
| 69 | "sni-disabled-ip": {addr, "", fmt.Errorf("failed to connect: x509: cannot validate certificate for %s because it doesn't contain any IP SANs", addr)}, |
| 70 | "sni-enabled-ip": {addr, serverName, nil}, |
| 71 | } |
| 72 | |
| 73 | for name, tc := range tests { |
| 74 | t.Run(name, func(t *testing.T) { |
| 75 | _, err := getPeerCertificates(tc.addr, tc.serverName, "", false) |
| 76 | if err != nil { |
| 77 | if assert.NotNil(t, tc.err) { |
| 78 | assert.HasPrefix(t, err.Error(), tc.err.Error()) |
| 79 | } |
| 80 | } else { |
| 81 | assert.Nil(t, tc.err) |
| 82 | } |
| 83 | }) |
| 84 | } |
| 85 | } |