This repository has been archived by the owner on Nov 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
context.go
357 lines (299 loc) · 10.3 KB
/
context.go
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*
Copyright NetFoundry, Inc.
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
https://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 tests
import (
"crypto/sha1"
tls2 "crypto/tls"
"fmt"
"github.com/go-resty/resty/v2"
"github.com/golang/protobuf/proto"
"github.com/openziti/fabric/controller/api_impl"
"github.com/openziti/fabric/pb/mgmt_pb"
"github.com/openziti/fabric/router"
"github.com/openziti/foundation/channel2"
"github.com/openziti/foundation/identity/certtools"
"github.com/openziti/foundation/identity/identity"
"net"
"net/http"
"net/http/cookiejar"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Jeffail/gabs/v2"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/fabric/controller"
"github.com/openziti/foundation/transport"
"github.com/openziti/foundation/transport/quic"
"github.com/openziti/foundation/transport/tcp"
"github.com/openziti/foundation/transport/tls"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
)
const (
ControllerConfFile = "./testdata/config/ctrl.yml"
RouterConfFile = "./testdata/config/router-%v.yml"
)
func init() {
logOptions := pfxlog.DefaultOptions().
SetTrimPrefix("github.com/openziti/").
StartingToday()
pfxlog.GlobalInit(logrus.DebugLevel, logOptions)
pfxlog.SetFormatter(pfxlog.NewFormatter(logOptions))
_ = os.Setenv("ZITI_TRACE_ENABLED", "false")
transport.AddAddressParser(quic.AddressParser{})
transport.AddAddressParser(tls.AddressParser{})
transport.AddAddressParser(tcp.AddressParser{})
}
type TestContext struct {
fabricController *controller.Controller
Req *require.Assertions
managementApiClient *resty.Client
enabledJsonLogging bool
routers []*router.Router
testing *testing.T
LogLevel string
ControllerConfig *controller.Config
}
func NewTestContext(t *testing.T) *TestContext {
ret := &TestContext{
LogLevel: os.Getenv("ZITI_TEST_LOG_LEVEL"),
Req: require.New(t),
}
ret.testContextChanged(t)
return ret
}
// testContextChanged is used to update the *testing.T reference used by library
// level tests. Necessary because using the wrong *testing.T will cause go test library
// errors.
func (ctx *TestContext) testContextChanged(t *testing.T) {
ctx.testing = t
ctx.Req = require.New(t)
}
func (ctx *TestContext) T() *testing.T {
return ctx.testing
}
func (ctx *TestContext) NewTransport(i identity.Identity) *http.Transport {
var tlsClientConfig *tls2.Config
if i != nil {
tlsClientConfig = i.ClientTLSConfig()
}
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: tlsClientConfig,
}
}
func (ctx *TestContext) NewHttpClient(transport *http.Transport) *http.Client {
jar, err := cookiejar.New(&cookiejar.Options{})
ctx.Req.NoError(err)
return &http.Client{
Transport: transport,
CheckRedirect: nil,
Jar: jar,
Timeout: 2000 * time.Second,
}
}
func (ctx *TestContext) NewRestClient(i identity.Identity) *resty.Client {
return resty.NewWithClient(ctx.NewHttpClient(ctx.NewTransport(i)))
}
func (ctx *TestContext) NewRestClientWithDefaults() *resty.Client {
id, err := identity.LoadClientIdentity(
"./testdata/valid_client_cert/client.cert",
"./testdata/valid_client_cert/client.key",
"./testdata/ca/intermediate/certs/ca-chain.cert.pem")
ctx.Req.NoError(err)
return resty.NewWithClient(ctx.NewHttpClient(ctx.NewTransport(id)))
}
func (ctx *TestContext) StartServer() {
ctx.StartServerFor("default", true)
}
func (ctx *TestContext) StartServerFor(test string, clean bool) {
api_impl.OverrideRequestWrapper(nil) // clear possible wrapper from another test
if ctx.LogLevel != "" {
if level, err := logrus.ParseLevel(ctx.LogLevel); err == nil {
logrus.StandardLogger().SetLevel(level)
}
}
log := pfxlog.Logger()
_ = os.Mkdir("testdata", os.FileMode(0755))
if clean {
err := filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error {
if err == nil {
if !info.IsDir() && strings.HasPrefix(info.Name(), test+".db") {
pfxlog.Logger().Infof("removing test bolt file or backup: %v", path)
err = os.Remove(path)
}
}
return err
})
ctx.Req.NoError(err)
}
err := os.Setenv("ZITI_TEST_DB", test)
ctx.Req.NoError(err)
log.Info("loading config")
config, err := controller.LoadConfig(ControllerConfFile)
ctx.Req.NoError(err)
ctx.ControllerConfig = config
log.Info("creating fabric controller")
ctx.fabricController, err = controller.NewController(config, NewVersionProviderTest())
ctx.Req.NoError(err)
go func() {
err = ctx.fabricController.Run()
ctx.Req.NoError(err)
}()
err = ctx.waitForCtrlPort(time.Second * 5)
ctx.Req.NoError(err)
ctx.requireRestPort(time.Second * 5)
}
func (ctx *TestContext) startRouter(index uint8) {
config, err := router.LoadConfig(fmt.Sprintf(RouterConfFile, index))
ctx.Req.NoError(err)
r := router.Create(config, NewVersionProviderTest())
ctx.Req.NoError(r.Start())
ctx.routers = append(ctx.routers, r)
}
func (ctx *TestContext) shutdownRouter() {
for _, r := range ctx.routers {
ctx.Req.NoError(r.Shutdown())
}
ctx.routers = nil
}
func (ctx *TestContext) waitForCtrlPort(duration time.Duration) error {
return ctx.waitForPort("127.0.0.1:6363", duration)
}
func (ctx *TestContext) requireRestPort(duration time.Duration) {
err := ctx.waitForPort("127.0.0.1:1281", duration)
ctx.Req.NoError(err)
}
func (ctx *TestContext) waitForPort(address string, duration time.Duration) error {
now := time.Now()
endTime := now.Add(duration)
maxWait := duration
for {
conn, err := net.DialTimeout("tcp", address, maxWait)
if err == nil {
_ = conn.Close()
return nil
}
now = time.Now()
if !now.Before(endTime) {
return err
}
maxWait = endTime.Sub(now)
time.Sleep(10 * time.Millisecond)
}
}
func (ctx *TestContext) Teardown() {
pfxlog.Logger().Info("tearing down test context")
ctx.shutdownRouter()
if ctx.fabricController != nil {
ctx.fabricController.Shutdown()
ctx.fabricController = nil
}
}
func (ctx *TestContext) validateDateFieldsForCreate(start time.Time, jsonEntity *gabs.Container) time.Time {
// we lose a little time resolution, so if it's in the same millisecond, it's ok
start = start.Add(-time.Millisecond)
now := time.Now().Add(time.Millisecond)
createdAt, updatedAt := ctx.getEntityDates(jsonEntity)
ctx.Req.Equal(createdAt, updatedAt)
ctx.Req.True(start.Before(createdAt) || start.Equal(createdAt), "%v should be before or equal to %v", start, createdAt)
ctx.Req.True(now.After(createdAt) || now.Equal(createdAt), "%v should be after or equal to %v", now, createdAt)
return createdAt
}
func (ctx *TestContext) getEntityDates(jsonEntity *gabs.Container) (time.Time, time.Time) {
createdAtStr := jsonEntity.S("createdAt").Data().(string)
updatedAtStr := jsonEntity.S("updatedAt").Data().(string)
ctx.Req.NotNil(createdAtStr)
ctx.Req.NotNil(updatedAtStr)
createdAt, err := time.Parse(time.RFC3339, createdAtStr)
ctx.Req.NoError(err)
updatedAt, err := time.Parse(time.RFC3339, updatedAtStr)
ctx.Req.NoError(err)
return createdAt, updatedAt
}
func (ctx *TestContext) validateDateFieldsForUpdate(start time.Time, origCreatedAt time.Time, jsonEntity *gabs.Container) time.Time {
// we lose a little time resolution, so if it's in the same millisecond, it's ok
start = start.Add(-time.Millisecond)
now := time.Now().Add(time.Millisecond)
createdAt, updatedAt := ctx.getEntityDates(jsonEntity)
ctx.Req.Equal(origCreatedAt, createdAt)
ctx.Req.True(createdAt.Before(updatedAt))
ctx.Req.True(start.Before(updatedAt) || start.Equal(updatedAt))
ctx.Req.True(now.After(updatedAt) || now.Equal(updatedAt))
return createdAt
}
func (ctx *TestContext) createMgmtClient() *MgmtClient {
id, err := identity.LoadClientIdentity(
"./testdata/valid_client_cert/client.cert",
"./testdata/valid_client_cert/client.key",
"./testdata/ca/intermediate/certs/ca-chain.cert.pem")
ctx.Req.NoError(err)
mgmtAddress, err := transport.ParseAddress("tls:localhost:10001")
ctx.Req.NoError(err)
dialer := channel2.NewClassicDialer(id, mgmtAddress, nil)
ch, err := channel2.NewChannel("mgmt", dialer, nil)
ctx.Req.NoError(err)
return &MgmtClient{
TestContext: ctx,
ch: ch,
}
}
type MgmtClient struct {
*TestContext
ch channel2.Channel
}
func (self *MgmtClient) ListServices(query string) []*mgmt_pb.Service {
request := &mgmt_pb.ListServicesRequest{
Query: query,
}
body, err := proto.Marshal(request)
self.Req.NoError(err)
requestMsg := channel2.NewMessage(int32(mgmt_pb.ContentType_ListServicesRequestType), body)
responseMsg, err := self.ch.SendAndWaitWithTimeout(requestMsg, 5*time.Second)
self.Req.NoError(err)
self.Req.Equal(responseMsg.ContentType, int32(mgmt_pb.ContentType_ListServicesResponseType))
response := &mgmt_pb.ListServicesResponse{}
err = proto.Unmarshal(responseMsg.Body, response)
self.Req.NoError(err)
return response.Services
}
func (self *MgmtClient) EnrollRouter(id string, name string, certFile string) {
cert, err := certtools.LoadCertFromFile(certFile)
self.Req.NoError(err)
request := &mgmt_pb.CreateRouterRequest{
Router: &mgmt_pb.Router{
Id: id,
Name: name,
Fingerprint: fmt.Sprintf("%x", sha1.Sum(cert[0].Raw)),
},
}
body, err := proto.Marshal(request)
self.Req.NoError(err)
requestMsg := channel2.NewMessage(int32(mgmt_pb.ContentType_CreateRouterRequestType), body)
responseMsg, err := self.ch.SendAndWaitWithTimeout(requestMsg, 5*time.Second)
self.Req.NoError(err)
self.Req.Equal(responseMsg.ContentType, int32(channel2.ContentTypeResultType), "unexpected response type %v", responseMsg.ContentType)
result := channel2.UnmarshalResult(responseMsg)
self.Req.True(result.Success, "expected success, msg: %v", result.Message)
}