File: ntpmonitor_test.go

package info (click to toggle)
golang-github-sigstore-timestamp-authority 1.2.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 824 kB
  • sloc: makefile: 113; sh: 42
file content (307 lines) | stat: -rw-r--r-- 8,907 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
297
298
299
300
301
302
303
304
305
306
307
//
// Copyright 2022 The Sigstore 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 ntpmonitor

import (
	"errors"
	"testing"
	"time"

	"github.com/beevik/ntp"
	"github.com/prometheus/client_golang/prometheus/testutil"
	pkgapi "github.com/sigstore/timestamp-authority/pkg/api"
)

type MockNTPClient struct {
	// add the names of servers that MockNTPClient#QueryWithOptions should
	// always return an error response for
	ignoredServers map[string]string
}

func (c MockNTPClient) QueryWithOptions(srv string, _ ntp.QueryOptions) (*ntp.Response, error) {
	if _, ok := c.ignoredServers[srv]; ok {
		return nil, errors.New("failed to query NTP server")
	}

	return &ntp.Response{
		ClockOffset: 1,
		Time:        time.Now(),
	}, nil
}

type driftedTimeNTPClient struct {
	driftedOffset time.Duration
}

func (c driftedTimeNTPClient) QueryWithOptions(_ string, _ ntp.QueryOptions) (*ntp.Response, error) {
	return &ntp.Response{
		ClockOffset: c.driftedOffset,
		Time:        time.Now(),
	}, nil
}

func TestNewFromConfig(t *testing.T) {
	var cfg Config
	var nm *NTPMonitor
	var err error

	// No servers listed
	nm, err = NewFromConfig(&cfg)
	if nm != nil {
		t.Error("non expected monitor returned")
	}
	if err != ErrTooFewServers {
		t.Errorf("expected error %s got %s", ErrTooFewServers, err)
	}

	// Number of servers are smaller than requested
	cfg.Servers = append(cfg.Servers, "foo.bar")
	cfg.NumServers = 2
	nm, err = NewFromConfig(&cfg)
	if nm != nil {
		t.Error("non expected monitor returned")
	}
	if err != ErrTooFewServers {
		t.Errorf("expected error %s got %s", ErrTooFewServers, err)
	}

	// Add a new server so len(servers) == num servers
	cfg.Servers = append(cfg.Servers, "foo.bar")

	// Threshold smaller than num servers
	cfg.ServerThreshold = 3
	nm, err = NewFromConfig(&cfg)
	if nm != nil {
		t.Error("non expected monitor returned")
	}
	if err != ErrTooFewServers {
		t.Errorf("expected error %s got %s", ErrTooFewServers, err)
	}

	// Set threshold to zero
	cfg.ServerThreshold = 0
	nm, err = NewFromConfig(&cfg)
	if nm != nil {
		t.Error("non expected monitor returned")
	}
	if err != ErrThreshold {
		t.Errorf("expected error %s got %s", ErrThreshold, err)
	}

	// Set threshold to two (len of servers)
	cfg.ServerThreshold = 2

	// Max delta is 0
	nm, err = NewFromConfig(&cfg)
	if nm != nil {
		t.Error("non expected monitor returned")
	}
	if err != ErrDeltaTooSmall {
		t.Errorf("expected error %s got %s", ErrDeltaTooSmall, err)
	}

	// Max delta is greater than request timeout
	cfg.RequestTimeout = 1
	nm, err = NewFromConfig(&cfg)
	if nm != nil {
		t.Error("non expected monitor returned")
	}
	if err != ErrDeltaTooSmall {
		t.Errorf("expected error %s got %s", ErrDeltaTooSmall, err)
	}

	// Valid config
	cfg.MaxTimeDelta = 1
	nm, err = NewFromConfig(&cfg)
	if nm == nil {
		t.Error("expected monitor returned")
	}
	if err != nil {
		t.Errorf("unexpected error %s", err)
	}
}

func TestNTPMonitorQueryNTPServer(t *testing.T) {
	mockNTP := MockNTPClient{}
	failNTP := MockNTPClient{
		ignoredServers: map[string]string{
			"s1": "",
		},
	}

	testCases := []struct {
		name                          string
		client                        MockNTPClient
		config                        Config
		expectedSuccessfulMetricCount int
		expectedFailedMetricCount     int
		expectTestToPass              bool
	}{
		{
			name:   "Successfully query NTP server",
			client: mockNTP,
			config: Config{
				Servers:         []string{"s1"},
				NumServers:      1,
				RequestAttempts: 1,
				ServerThreshold: 1,
				RequestTimeout:  1,
				MaxTimeDelta:    1,
			},
			expectedSuccessfulMetricCount: 1,
			expectedFailedMetricCount:     0,
			expectTestToPass:              true,
		},
		{
			name:   "Fail to query NTP server",
			client: failNTP,
			config: Config{
				Servers:         []string{"s1"},
				NumServers:      1,
				RequestAttempts: 3,
				ServerThreshold: 1,
				RequestTimeout:  5,
				MaxTimeDelta:    6,
			},
			expectedSuccessfulMetricCount: 0,
			expectedFailedMetricCount:     3,
			expectTestToPass:              false,
		},
	}

	for _, tc := range testCases {
		// reset the CounterVec before each test case so we can check for
		// the expected metric count
		pkgapi.MetricNTPSyncCount.Reset()
		monitor, err := NewFromConfigWithClient(&tc.config, tc.client)
		if err != nil {
			t.Fatalf("unexpectedly failed to create NTP monitor: %v", err)
		}

		resp, err := monitor.queryNTPServer("s1")
		if tc.expectTestToPass && err != nil {
			t.Errorf("test '%s' unexpectedly failed with non-nil error: %v", tc.name, err)
		}
		if tc.expectTestToPass && resp == nil {
			t.Errorf("test '%s' unexpectedly failed with nil ntp.Response", tc.name)
		}
		if !tc.expectTestToPass && err == nil {
			t.Errorf("test '%s' unexpectedly passed with a nil error", tc.name)
		}
		// check that the actual metric value was incremented by one as expected
		successfulMetricCount := testutil.ToFloat64(pkgapi.MetricNTPSyncCount.With(map[string]string{
			"failed": "false",
			"host":   "s1",
		}))
		if tc.expectedSuccessfulMetricCount != int(successfulMetricCount) {
			t.Errorf("test '%s' unexpectedly failed with wrong successful metric value %d, expected %d", tc.name, int(successfulMetricCount), tc.expectedSuccessfulMetricCount)
		}
		// check that the actual metric value was incremented by one as expected
		failedMetricCount := testutil.ToFloat64(pkgapi.MetricNTPSyncCount.With(map[string]string{
			"failed": "true",
			"host":   "s1",
		}))
		if tc.expectedFailedMetricCount != int(failedMetricCount) {
			t.Errorf("test '%s' unexpectedly failed with wrong failed metric value %d, expected %d", tc.name, int(failedMetricCount), tc.expectedFailedMetricCount)
		}
	}
}

func TestNTPMonitorQueryServers(t *testing.T) {
	mockNTP := MockNTPClient{}
	failNTP := MockNTPClient{
		ignoredServers: map[string]string{"s1": "", "s2": "", "s3": ""},
	}
	partialFailNTP := MockNTPClient{
		ignoredServers: map[string]string{"s2": "", "s3": ""},
	}

	offsetDuration, err := time.ParseDuration("5s")
	if err != nil {
		t.Fatalf("unexpected failed to parse duration: %v", err)
	}

	driftedNTP := driftedTimeNTPClient{
		driftedOffset: offsetDuration,
	}

	testCases := []struct {
		name                       string
		client                     NTPClient
		serverThreshold            int
		maxTimeDelta               int
		expectEnoughServerResponse bool
		expectValidServerResponse  bool
	}{
		{
			name:                       "Successfully query all NTP servers",
			client:                     mockNTP,
			serverThreshold:            3,
			maxTimeDelta:               3,
			expectEnoughServerResponse: true,
			expectValidServerResponse:  true,
		},
		{
			name:                       "Receive too few server responses",
			client:                     partialFailNTP,
			serverThreshold:            2,
			maxTimeDelta:               5,
			expectEnoughServerResponse: false,
			expectValidServerResponse:  false,
		},
		{
			name:                       "Receive too many drifted time responses",
			client:                     driftedNTP,
			serverThreshold:            2,
			maxTimeDelta:               2,
			expectEnoughServerResponse: true,
			expectValidServerResponse:  false,
		},
		{
			name:                       "Fail to receive any responses",
			client:                     failNTP,
			serverThreshold:            1,
			maxTimeDelta:               4,
			expectEnoughServerResponse: false,
			expectValidServerResponse:  false,
		},
	}
	for _, tc := range testCases {
		monitor, err := NewFromConfigWithClient(&Config{
			Servers:         []string{"s1", "s2", "s3", "s4", "s5", "s6"},
			NumServers:      3,
			Period:          1,
			RequestAttempts: 1,
			RequestTimeout:  1,
			ServerThreshold: tc.serverThreshold,
			MaxTimeDelta:    tc.maxTimeDelta,
		}, tc.client)
		if err != nil {
			t.Fatalf("unexpectedly failed to create NTP monitor: %v", err)
		}

		delta := time.Duration(tc.maxTimeDelta) * time.Second
		testedServers := []string{"s1", "s2", "s3"}

		responses := monitor.queryServers(delta, testedServers)
		if tc.expectEnoughServerResponse && responses.tooFewServerResponses {
			t.Errorf("test '%s' unexpectedly failed with too few server responses", tc.name)
		}
		if tc.expectValidServerResponse && responses.tooManyInvalidResponses {
			t.Errorf("test '%s' unexpectedly failed with too many invalid responses", tc.name)
		}
	}
}