| 1 |
package internal |
| 2 |
|
| 3 |
import ( |
| 4 |
"net/http" |
| 5 |
"net/http/httptest" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"github.com/google/go-tpm-tools/internal/test" |
| 9 |
) |
| 10 |
|
| 11 |
var localClient = http.DefaultClient |
| 12 |
|
| 13 |
func TestFetchIssuingCertificateSucceeds(t *testing.T) { |
| 14 |
testCA, caKey := test.GetTestCert(t, nil, nil, nil) |
| 15 |
|
| 16 |
ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { |
| 17 |
rw.WriteHeader(http.StatusOK) |
| 18 |
rw.Write(testCA.Raw) |
| 19 |
})) |
| 20 |
defer ts.Close() |
| 21 |
|
| 22 |
leafCert, _ := test.GetTestCert(t, []string{"invalid.URL", ts.URL}, testCA, caKey) |
| 23 |
|
| 24 |
cert, err := fetchIssuingCertificate(localClient, leafCert) |
| 25 |
if err != nil || cert == nil { |
| 26 |
t.Errorf("fetchIssuingCertificate() did not find valid intermediate cert: %v", err) |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
func TestFetchIssuingCertificateReturnsErrorIfMalformedCertificateFound(t *testing.T) { |
| 31 |
ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { |
| 32 |
rw.WriteHeader(http.StatusOK) |
| 33 |
rw.Write([]byte("these are some random bytes")) |
| 34 |
})) |
| 35 |
defer ts.Close() |
| 36 |
|
| 37 |
testCA, caKey := test.GetTestCert(t, nil, nil, nil) |
| 38 |
leafCert, _ := test.GetTestCert(t, []string{ts.URL}, testCA, caKey) |
| 39 |
|
| 40 |
_, err := fetchIssuingCertificate(localClient, leafCert) |
| 41 |
if err == nil { |
| 42 |
t.Fatal("expected fetchIssuingCertificate to fail with malformed cert") |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
func TestGetCertificateChainSucceeds(t *testing.T) { |
| 47 |
// Create CA and corresponding server. |
| 48 |
testCA, caKey := test.GetTestCert(t, nil, nil, nil) |
| 49 |
|
| 50 |
caServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { |
| 51 |
rw.WriteHeader(http.StatusOK) |
| 52 |
rw.Write(testCA.Raw) |
| 53 |
})) |
| 54 |
|
| 55 |
defer caServer.Close() |
| 56 |
|
| 57 |
// Create intermediate cert and corresponding server. |
| 58 |
intermediateCert, intermediateKey := test.GetTestCert(t, []string{caServer.URL}, testCA, caKey) |
| 59 |
|
| 60 |
intermediateServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { |
| 61 |
rw.WriteHeader(http.StatusOK) |
| 62 |
rw.Write(intermediateCert.Raw) |
| 63 |
})) |
| 64 |
defer intermediateServer.Close() |
| 65 |
|
| 66 |
// Create leaf cert. |
| 67 |
leafCert, _ := test.GetTestCert(t, []string{intermediateServer.URL}, intermediateCert, intermediateKey) |
| 68 |
|
| 69 |
certChain, err := GetCertificateChain(leafCert, localClient) |
| 70 |
if err != nil { |
| 71 |
t.Fatal(err) |
| 72 |
} |
| 73 |
if len(certChain) != 2 { |
| 74 |
t.Fatalf("GetCertificateChain did not return the expected number of certificates: got %v, want 2", len(certChain)) |
| 75 |
} |
| 76 |
} |