File: ocsp_test.go

package info (click to toggle)
golang-github-notaryproject-notation-core-go 1.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,036 kB
  • sloc: makefile: 22
file content (296 lines) | stat: -rw-r--r-- 11,894 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ocsp

import (
	"context"
	"crypto/x509"
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"testing"
	"time"

	"github.com/notaryproject/notation-core-go/revocation/result"
	"github.com/notaryproject/notation-core-go/testhelper"
	"golang.org/x/crypto/ocsp"
)

func validateEquivalentCertResults(certResults, expectedCertResults []*result.CertRevocationResult, t *testing.T) {
	if len(certResults) != len(expectedCertResults) {
		t.Errorf("Length of certResults (%d) did not match expected length (%d)", len(certResults), len(expectedCertResults))
		return
	}
	for i, certResult := range certResults {
		if certResult.Result != expectedCertResults[i].Result {
			t.Errorf("Expected certResults[%d].Result to be %s, but got %s", i, expectedCertResults[i].Result, certResult.Result)
		}
		if len(certResult.ServerResults) != len(expectedCertResults[i].ServerResults) {
			t.Errorf("Length of certResults[%d].ServerResults (%d) did not match expected length (%d)", i, len(certResult.ServerResults), len(expectedCertResults[i].ServerResults))
			return
		}
		for j, serverResult := range certResult.ServerResults {
			if serverResult.Result != expectedCertResults[i].ServerResults[j].Result {
				t.Errorf("Expected certResults[%d].ServerResults[%d].Result to be %s, but got %s", i, j, expectedCertResults[i].ServerResults[j].Result, serverResult.Result)
			}
			if serverResult.Server != expectedCertResults[i].ServerResults[j].Server {
				t.Errorf("Expected certResults[%d].ServerResults[%d].Server to be %s, but got %s", i, j, expectedCertResults[i].ServerResults[j].Server, serverResult.Server)
			}
			if serverResult.Error == nil {
				if expectedCertResults[i].ServerResults[j].Error == nil {
					continue
				}
				t.Errorf("certResults[%d].ServerResults[%d].Error was nil, but expected %v", i, j, expectedCertResults[i].ServerResults[j].Error)
			} else if expectedCertResults[i].ServerResults[j].Error == nil {
				t.Errorf("Unexpected error for certResults[%d].ServerResults[%d].Error: %v", i, j, serverResult.Error)
			} else if serverResult.Error.Error() != expectedCertResults[i].ServerResults[j].Error.Error() {
				t.Errorf("Expected certResults[%d].ServerResults[%d].Error to be %v, but got %v", i, j, expectedCertResults[i].ServerResults[j].Error, serverResult.Error)
			}
		}
	}
}

func getOKCertResult(server string) *result.CertRevocationResult {
	return &result.CertRevocationResult{
		Result: result.ResultOK,
		ServerResults: []*result.ServerResult{
			result.NewServerResult(result.ResultOK, server, nil),
		},
	}
}

func TestCheckStatus(t *testing.T) {
	revokableCertTuple := testhelper.GetRevokableRSALeafCertificate()
	revokableIssuerTuple := testhelper.GetRSARootCertificate()
	ocspServer := revokableCertTuple.Cert.OCSPServer[0]
	revokableChain := []*x509.Certificate{revokableCertTuple.Cert, revokableIssuerTuple.Cert}
	testChain := []testhelper.RSACertTuple{revokableCertTuple, revokableIssuerTuple}
	ctx := context.Background()

	t.Run("check non-revoked cert", func(t *testing.T) {
		client := testhelper.MockClient(testChain, []ocsp.ResponseStatus{ocsp.Good}, nil, true)
		opts := CertCheckStatusOptions{
			SigningTime: time.Now(),
			HTTPClient:  client,
		}

		certResult := CertCheckStatus(ctx, revokableChain[0], revokableChain[1], opts)
		expectedCertResults := []*result.CertRevocationResult{getOKCertResult(ocspServer)}
		validateEquivalentCertResults([]*result.CertRevocationResult{certResult}, expectedCertResults, t)
	})
	t.Run("check cert with Unknown OCSP response", func(t *testing.T) {
		client := testhelper.MockClient(testChain, []ocsp.ResponseStatus{ocsp.Unknown}, nil, true)
		opts := CertCheckStatusOptions{
			SigningTime: time.Now(),
			HTTPClient:  client,
		}

		certResult := CertCheckStatus(ctx, revokableChain[0], revokableChain[1], opts)
		expectedCertResults := []*result.CertRevocationResult{{
			Result: result.ResultUnknown,
			ServerResults: []*result.ServerResult{
				result.NewServerResult(result.ResultUnknown, ocspServer, UnknownStatusError{}),
			},
		}}
		validateEquivalentCertResults([]*result.CertRevocationResult{certResult}, expectedCertResults, t)
	})
	t.Run("check OCSP revoked cert", func(t *testing.T) {
		client := testhelper.MockClient(testChain, []ocsp.ResponseStatus{ocsp.Revoked}, nil, true)
		opts := CertCheckStatusOptions{
			SigningTime: time.Now(),
			HTTPClient:  client,
		}

		certResult := CertCheckStatus(ctx, revokableChain[0], revokableChain[1], opts)
		expectedCertResults := []*result.CertRevocationResult{{
			Result: result.ResultRevoked,
			ServerResults: []*result.ServerResult{
				result.NewServerResult(result.ResultRevoked, ocspServer, RevokedError{}),
			},
		}}
		validateEquivalentCertResults([]*result.CertRevocationResult{certResult}, expectedCertResults, t)
	})
	t.Run("check OCSP future revoked cert", func(t *testing.T) {
		revokedTime := time.Now().Add(time.Hour)
		client := testhelper.MockClient(testChain, []ocsp.ResponseStatus{ocsp.Revoked}, &revokedTime, true)
		opts := CertCheckStatusOptions{
			SigningTime: time.Now(),
			HTTPClient:  client,
		}

		certResult := CertCheckStatus(ctx, revokableChain[0], revokableChain[1], opts)
		expectedCertResults := []*result.CertRevocationResult{getOKCertResult(ocspServer)}
		validateEquivalentCertResults([]*result.CertRevocationResult{certResult}, expectedCertResults, t)
	})

	t.Run("certificate doesn't support OCSP", func(t *testing.T) {
		ocspResult := CertCheckStatus(ctx, &x509.Certificate{}, revokableIssuerTuple.Cert, CertCheckStatusOptions{})
		expectedResult := &result.CertRevocationResult{
			Result:        result.ResultNonRevokable,
			ServerResults: []*result.ServerResult{toServerResult("", NoServerError{})},
		}

		validateEquivalentCertResults([]*result.CertRevocationResult{ocspResult}, []*result.CertRevocationResult{expectedResult}, t)
	})
}

func TestCheckStatusFromServer(t *testing.T) {
	revokableCertTuple := testhelper.GetRevokableRSALeafCertificate()
	revokableIssuerTuple := testhelper.GetRSARootCertificate()
	ctx := context.Background()

	t.Run("server url is not http", func(t *testing.T) {
		server := "https://localhost.test"
		serverResult := checkStatusFromServer(ctx, revokableCertTuple.Cert, revokableIssuerTuple.Cert, server, CertCheckStatusOptions{})
		expectedResult := toServerResult(server, GenericError{Err: fmt.Errorf("OCSPServer protocol %s is not supported", "https")})
		if serverResult.Result != expectedResult.Result {
			t.Errorf("Expected Result to be %s, but got %s", expectedResult.Result, serverResult.Result)
		}
		if serverResult.Server != expectedResult.Server {
			t.Errorf("Expected Server to be %s, but got %s", expectedResult.Server, serverResult.Server)
		}
		if serverResult.Error == nil {
			t.Errorf("Expected Error to be %v, but got nil", expectedResult.Error)
		} else if serverResult.Error.Error() != expectedResult.Error.Error() {
			t.Errorf("Expected Error to be %v, but got %v", expectedResult.Error, serverResult.Error)
		}
	})

	t.Run("request error", func(t *testing.T) {
		server := "http://localhost.test"
		serverResult := checkStatusFromServer(ctx, revokableCertTuple.Cert, revokableIssuerTuple.Cert, server, CertCheckStatusOptions{
			HTTPClient: &http.Client{
				Transport: &failedTransport{},
			},
		})
		errorMessage := "failed to execute request"
		if !strings.Contains(serverResult.Error.Error(), errorMessage) {
			t.Errorf("Expected Error to contain %v, but got %v", errorMessage, serverResult.Error)
		}
	})

	t.Run("ocsp expired", func(t *testing.T) {
		client := testhelper.MockClient([]testhelper.RSACertTuple{revokableCertTuple, revokableIssuerTuple}, []ocsp.ResponseStatus{ocsp.Good}, nil, true)
		server := "http://localhost.test/expired_ocsp"
		serverResult := checkStatusFromServer(ctx, revokableCertTuple.Cert, revokableIssuerTuple.Cert, server, CertCheckStatusOptions{
			HTTPClient: client,
		})
		errorMessage := "expired OCSP response"
		if !strings.Contains(serverResult.Error.Error(), errorMessage) {
			t.Errorf("Expected Error to contain %v, but got %v", errorMessage, serverResult.Error)
		}
	})

	t.Run("ocsp request roundtrip failed", func(t *testing.T) {
		client := testhelper.MockClient([]testhelper.RSACertTuple{revokableCertTuple, revokableIssuerTuple}, []ocsp.ResponseStatus{ocsp.Good}, nil, true)
		server := "http://localhost.test"
		serverResult := checkStatusFromServer(nil, revokableCertTuple.Cert, revokableIssuerTuple.Cert, server, CertCheckStatusOptions{
			HTTPClient: client,
		})
		errorMessage := "net/http: nil Context"
		if !strings.Contains(serverResult.Error.Error(), errorMessage) {
			t.Errorf("Expected Error to contain %v, but got %v", errorMessage, serverResult.Error)
		}
	})

	t.Run("ocsp request roundtrip timeout", func(t *testing.T) {
		server := "http://localhost.test"
		serverResult := checkStatusFromServer(ctx, revokableCertTuple.Cert, revokableIssuerTuple.Cert, server, CertCheckStatusOptions{
			HTTPClient: &http.Client{
				Timeout: 1 * time.Second,
				Transport: &failedTransport{
					timeout: true,
				},
			},
		})
		errorMessage := "exceeded timeout threshold of 1.00 seconds for OCSP check"
		if !strings.Contains(serverResult.Error.Error(), errorMessage) {
			t.Errorf("Expected Error to contain %v, but got %v", errorMessage, serverResult.Error)
		}
	})
}

func TestPostRequest(t *testing.T) {
	t.Run("failed to generate request", func(t *testing.T) {
		_, err := postRequest(nil, nil, "http://localhost.test", &http.Client{
			Transport: &failedTransport{},
		})
		expectedErrMsg := "net/http: nil Context"
		if err == nil || err.Error() != expectedErrMsg {
			t.Errorf("Expected error %s, but got %s", expectedErrMsg, err)
		}
	})

	t.Run("failed to execute request", func(t *testing.T) {
		_, err := postRequest(context.Background(), nil, "http://localhost.test", &http.Client{
			Transport: &failedTransport{},
		})
		expectedErrMsg := "Post \"http://localhost.test\": failed to execute request"
		if err == nil || err.Error() != expectedErrMsg {
			t.Errorf("Expected error %s, but got %s", expectedErrMsg, err)
		}
	})
}

func TestExecuteOCSPCheck(t *testing.T) {
	revokableCertTuple := testhelper.GetRevokableRSALeafCertificate()
	revokableIssuerTuple := testhelper.GetRSARootCertificate()
	ctx := context.Background()

	t.Run("http response status is not 200", func(t *testing.T) {
		_, err := executeOCSPCheck(ctx, revokableCertTuple.Cert, revokableIssuerTuple.Cert, "localhost.test", CertCheckStatusOptions{
			HTTPClient: &http.Client{
				Transport: &failedTransport{
					statusCode: http.StatusNotFound,
				},
			},
		})
		expectedErrMsg := "failed to retrieve OCSP: response had status code 404"
		if err == nil || err.Error() != expectedErrMsg {
			t.Errorf("Expected error %s, but got %s", expectedErrMsg, err)
		}
	})
}

type testTimeoutError struct{}

func (e testTimeoutError) Error() string {
	return "test timeout"
}

func (e testTimeoutError) Timeout() bool {
	return true
}

type failedTransport struct {
	timeout    bool
	statusCode int
}

func (f *failedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	if f.timeout {
		return nil, &url.Error{
			Err: testTimeoutError{},
		}
	}

	if f.statusCode != 0 {
		return &http.Response{
			StatusCode: f.statusCode,
		}, nil
	}

	return nil, fmt.Errorf("failed to execute request")
}