forked from notaryproject/notary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
402 lines (345 loc) · 12.2 KB
/
server_test.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package server
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
_ "github.com/docker/distribution/registry/auth/silly"
"github.com/stretchr/testify/require"
"github.com/theupdateframework/notary"
"github.com/theupdateframework/notary/server/storage"
store "github.com/theupdateframework/notary/storage"
"github.com/theupdateframework/notary/tuf/data"
"github.com/theupdateframework/notary/tuf/signed"
"github.com/theupdateframework/notary/tuf/testutils"
tufutils "github.com/theupdateframework/notary/tuf/utils"
"github.com/theupdateframework/notary/utils"
"golang.org/x/net/context"
)
func TestRunBadAddr(t *testing.T) {
err := Run(
context.Background(),
Config{
Addr: "testAddr",
Trust: signed.NewEd25519(),
},
)
require.Error(t, err, "Passed bad addr, Run should have failed")
}
func TestRunReservedPort(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err := Run(
ctx,
Config{
Addr: "localhost:80",
Trust: signed.NewEd25519(),
},
)
require.Error(t, err)
require.IsType(t, &net.OpError{}, err)
require.True(
t,
strings.Contains(err.Error(), "bind: permission denied"),
"Received unexpected err: %s",
err.Error(),
)
}
func TestRepoPrefixMatches(t *testing.T) {
var gun data.GUN = "docker.io/notary"
meta, cs, err := testutils.NewRepoMetadata(gun)
require.NoError(t, err)
ctx := context.WithValue(context.Background(), notary.CtxKeyMetaStore, storage.NewMemStorage())
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)
snChecksumBytes := sha256.Sum256(meta[data.CanonicalSnapshotRole])
// successful gets
handler := RootHandler(ctx, nil, cs, nil, nil, []string{"docker.io"})
ts := httptest.NewServer(handler)
url := fmt.Sprintf("%s/v2/%s/_trust/tuf/", ts.URL, gun)
uploader, err := store.NewHTTPStore(url, "", "json", "key", http.DefaultTransport)
require.NoError(t, err)
// uploading is cool
require.NoError(t, uploader.SetMulti(data.MetadataRoleMapToStringMap(meta)))
// getting is cool
_, err = uploader.GetSized(data.CanonicalSnapshotRole.String(), notary.MaxDownloadSize)
require.NoError(t, err)
_, err = uploader.GetSized(
tufutils.ConsistentName(data.CanonicalSnapshotRole.String(), snChecksumBytes[:]), notary.MaxDownloadSize)
require.NoError(t, err)
_, err = uploader.GetKey(data.CanonicalTimestampRole)
require.NoError(t, err)
// the httpstore doesn't actually delete all, so we do it manually
req, err := http.NewRequest("DELETE", url, nil)
require.NoError(t, err)
res, err := http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
}
func TestRepoPrefixDoesNotMatch(t *testing.T) {
var gun data.GUN = "docker.io/notary"
meta, cs, err := testutils.NewRepoMetadata(gun)
require.NoError(t, err)
s := storage.NewMemStorage()
ctx := context.WithValue(context.Background(), notary.CtxKeyMetaStore, s)
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)
snChecksumBytes := sha256.Sum256(meta[data.CanonicalSnapshotRole])
// successful gets
handler := RootHandler(ctx, nil, cs, nil, nil, []string{"nope"})
ts := httptest.NewServer(handler)
url := fmt.Sprintf("%s/v2/%s/_trust/tuf/", ts.URL, gun)
uploader, err := store.NewHTTPStore(url, "", "json", "key", http.DefaultTransport)
require.NoError(t, err)
require.Error(t, uploader.SetMulti(data.MetadataRoleMapToStringMap(meta)))
// update the storage so we don't fail just because the metadata is missing
for _, roleName := range data.BaseRoles {
require.NoError(t, s.UpdateCurrent(gun, storage.MetaUpdate{
Role: roleName,
Data: meta[roleName],
Version: 1,
}))
}
_, err = uploader.GetSized(data.CanonicalSnapshotRole.String(), notary.MaxDownloadSize)
require.Error(t, err)
_, err = uploader.GetSized(
tufutils.ConsistentName(data.CanonicalSnapshotRole.String(), snChecksumBytes[:]), notary.MaxDownloadSize)
require.Error(t, err)
_, err = uploader.GetKey(data.CanonicalTimestampRole)
require.Error(t, err)
// the httpstore doesn't actually delete all, so we do it manually
req, err := http.NewRequest("DELETE", url, nil)
require.NoError(t, err)
res, err := http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusNotFound, res.StatusCode)
}
func TestMetricsEndpoint(t *testing.T) {
handler := RootHandler(context.Background(), nil, signed.NewEd25519(),
nil, nil, nil)
ts := httptest.NewServer(handler)
defer ts.Close()
res, err := http.Get(ts.URL + "/metrics")
require.NoError(t, err)
require.Equal(t, http.StatusOK, res.StatusCode)
}
// GetKeys supports only the timestamp and snapshot key endpoints
func TestGetKeysEndpoint(t *testing.T) {
ctx := context.WithValue(
context.Background(), notary.CtxKeyMetaStore, storage.NewMemStorage())
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)
handler := RootHandler(ctx, nil, signed.NewEd25519(), nil, nil, nil)
ts := httptest.NewServer(handler)
defer ts.Close()
rolesToStatus := map[data.RoleName]int{
data.CanonicalTimestampRole: http.StatusOK,
data.CanonicalSnapshotRole: http.StatusOK,
data.CanonicalTargetsRole: http.StatusNotFound,
data.CanonicalRootRole: http.StatusNotFound,
"somerandomrole": http.StatusNotFound,
}
for role, expectedStatus := range rolesToStatus {
res, err := http.Get(
fmt.Sprintf("%s/v2/gun/_trust/tuf/%s.key", ts.URL, role))
require.NoError(t, err)
require.Equal(t, expectedStatus, res.StatusCode)
}
}
// This just checks the URL routing is working correctly and cache headers are set correctly.
// More detailed tests for this path including negative
// tests are located in /server/handlers/
func TestGetRoleByHash(t *testing.T) {
store := storage.NewMemStorage()
ts := data.SignedTimestamp{
Signatures: make([]data.Signature, 0),
Signed: data.Timestamp{
SignedCommon: data.SignedCommon{
Type: data.TUFTypes[data.CanonicalTimestampRole],
Version: 1,
Expires: data.DefaultExpires(data.CanonicalTimestampRole),
},
},
}
j, err := json.Marshal(&ts)
require.NoError(t, err)
store.UpdateCurrent("gun", storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: 1,
Data: j,
})
checksumBytes := sha256.Sum256(j)
checksum := hex.EncodeToString(checksumBytes[:])
// create and add a newer timestamp. We're going to try and request
// the older version we created above.
ts = data.SignedTimestamp{
Signatures: make([]data.Signature, 0),
Signed: data.Timestamp{
SignedCommon: data.SignedCommon{
Type: data.TUFTypes[data.CanonicalTimestampRole],
Version: 2,
Expires: data.DefaultExpires(data.CanonicalTimestampRole),
},
},
}
newTS, err := json.Marshal(&ts)
require.NoError(t, err)
store.UpdateCurrent("gun", storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: 1,
Data: newTS,
})
ctx := context.WithValue(
context.Background(), notary.CtxKeyMetaStore, store)
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)
ccc := utils.NewCacheControlConfig(10, false)
handler := RootHandler(ctx, nil, signed.NewEd25519(), ccc, ccc, nil)
serv := httptest.NewServer(handler)
defer serv.Close()
res, err := http.Get(fmt.Sprintf(
"%s/v2/gun/_trust/tuf/%s.%s.json",
serv.URL,
data.CanonicalTimestampRole,
checksum,
))
require.NoError(t, err)
require.Equal(t, http.StatusOK, res.StatusCode)
// if content is equal, checksums are guaranteed to be equal
verifyGetResponse(t, res, j)
}
// This just checks the URL routing is working correctly and cache headers are set correctly.
// More detailed tests for this path including negative
// tests are located in /server/handlers/
func TestGetRoleByVersion(t *testing.T) {
store := storage.NewMemStorage()
ts := data.SignedTimestamp{
Signatures: make([]data.Signature, 0),
Signed: data.Timestamp{
SignedCommon: data.SignedCommon{
Type: data.TUFTypes[data.CanonicalTimestampRole],
Version: 1,
Expires: data.DefaultExpires(data.CanonicalTimestampRole),
},
},
}
j, err := json.Marshal(&ts)
require.NoError(t, err)
store.UpdateCurrent("gun", storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: 1,
Data: j,
})
// create and add a newer timestamp. We're going to try and request
// the older version we created above.
ts = data.SignedTimestamp{
Signatures: make([]data.Signature, 0),
Signed: data.Timestamp{
SignedCommon: data.SignedCommon{
Type: data.TUFTypes[data.CanonicalTimestampRole],
Version: 2,
Expires: data.DefaultExpires(data.CanonicalTimestampRole),
},
},
}
newTS, err := json.Marshal(&ts)
require.NoError(t, err)
store.UpdateCurrent("gun", storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: 1,
Data: newTS,
})
ctx := context.WithValue(
context.Background(), notary.CtxKeyMetaStore, store)
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)
ccc := utils.NewCacheControlConfig(10, false)
handler := RootHandler(ctx, nil, signed.NewEd25519(), ccc, ccc, nil)
serv := httptest.NewServer(handler)
defer serv.Close()
res, err := http.Get(fmt.Sprintf(
"%s/v2/gun/_trust/tuf/%d.%s.json",
serv.URL,
1,
data.CanonicalTimestampRole,
))
require.NoError(t, err)
require.Equal(t, http.StatusOK, res.StatusCode)
// if content is equal, checksums are guaranteed to be equal
verifyGetResponse(t, res, j)
}
// This just checks the URL routing is working correctly and cache headers are set correctly.
// More detailed tests for this path including negative
// tests are located in /server/handlers/
func TestGetCurrentRole(t *testing.T) {
store := storage.NewMemStorage()
metadata, _, err := testutils.NewRepoMetadata("gun")
require.NoError(t, err)
// need both the snapshot and the timestamp, because when getting the current
// timestamp the server checks to see if it's out of date (there's a new snapshot)
// and if so, generates a new one
store.UpdateCurrent("gun", storage.MetaUpdate{
Role: data.CanonicalSnapshotRole,
Version: 1,
Data: metadata[data.CanonicalSnapshotRole],
})
store.UpdateCurrent("gun", storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: 1,
Data: metadata[data.CanonicalTimestampRole],
})
ctx := context.WithValue(
context.Background(), notary.CtxKeyMetaStore, store)
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)
ccc := utils.NewCacheControlConfig(10, false)
handler := RootHandler(ctx, nil, signed.NewEd25519(), ccc, ccc, nil)
serv := httptest.NewServer(handler)
defer serv.Close()
res, err := http.Get(fmt.Sprintf(
"%s/v2/gun/_trust/tuf/%s.json",
serv.URL,
data.CanonicalTimestampRole,
))
require.NoError(t, err)
require.Equal(t, http.StatusOK, res.StatusCode)
verifyGetResponse(t, res, metadata[data.CanonicalTimestampRole])
}
// Verifies that the body is as expected and that there are cache control headers
func verifyGetResponse(t *testing.T, r *http.Response, expectedBytes []byte) {
body, err := ioutil.ReadAll(r.Body)
require.NoError(t, err)
require.True(t, bytes.Equal(expectedBytes, body))
require.NotEqual(t, "", r.Header.Get("Cache-Control"))
require.NotEqual(t, "", r.Header.Get("Last-Modified"))
require.Equal(t, "", r.Header.Get("Pragma"))
}
// RotateKey supports only timestamp and snapshot key rotation
func TestRotateKeyEndpoint(t *testing.T) {
ctx := context.WithValue(
context.Background(), notary.CtxKeyMetaStore, storage.NewMemStorage())
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)
ccc := utils.NewCacheControlConfig(10, false)
handler := RootHandler(ctx, nil, signed.NewEd25519(), ccc, ccc, nil)
ts := httptest.NewServer(handler)
defer ts.Close()
rolesToStatus := map[data.RoleName]int{
data.CanonicalTimestampRole: http.StatusOK,
data.CanonicalSnapshotRole: http.StatusOK,
data.CanonicalTargetsRole: http.StatusNotFound,
data.CanonicalRootRole: http.StatusNotFound,
"targets/delegation": http.StatusNotFound,
"somerandomrole": http.StatusNotFound,
}
var buf bytes.Buffer
for role, expectedStatus := range rolesToStatus {
res, err := http.Post(
fmt.Sprintf("%s/v2/gun/_trust/tuf/%s.key", ts.URL, role),
"text/plain", &buf)
require.NoError(t, err)
require.Equal(t, expectedStatus, res.StatusCode)
}
}