forked from taskcluster/taskcluster-proxy
/
authorization_test.go
411 lines (375 loc) · 10.9 KB
/
authorization_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
403
404
405
406
407
408
409
410
411
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"
"github.com/cenkalti/backoff"
"github.com/taskcluster/httpbackoff"
"github.com/taskcluster/slugid-go/slugid"
"github.com/taskcluster/taskcluster-client-go/tcclient"
)
var (
permCredentials = &tcclient.Credentials{
ClientId: os.Getenv("TASKCLUSTER_CLIENT_ID"),
AccessToken: os.Getenv("TASKCLUSTER_ACCESS_TOKEN"),
}
)
func init() {
httpbackoff.BackOffSettings = &backoff.ExponentialBackOff{
InitialInterval: 1 * time.Millisecond,
RandomizationFactor: 0.2,
Multiplier: 1.2,
MaxInterval: 5 * time.Millisecond,
MaxElapsedTime: 20 * time.Millisecond,
Clock: backoff.SystemClock,
}
}
type IntegrationTest func(t *testing.T, creds *tcclient.Credentials) *httptest.ResponseRecorder
func skipIfNoPermCreds(t *testing.T) {
if permCredentials.ClientId == "" {
t.Skip("TASKCLUSTER_CLIENT_ID not set - skipping test")
}
if permCredentials.AccessToken == "" {
t.Skip("TASKCLUSTER_ACCESS_TOKEN not set - skipping test")
}
}
func testWithPermCreds(t *testing.T, test IntegrationTest, expectedStatusCode int) {
skipIfNoPermCreds(t)
res := test(t, permCredentials)
checkStatusCode(
t,
res,
expectedStatusCode,
)
checkHeaders(
t,
res,
map[string]string{
"X-Taskcluster-Proxy-Version": version,
"X-Taskcluster-Proxy-Perm-ClientId": permCredentials.ClientId,
// N.B. the http library does not distinguish between header entries
// that have an empty "" value, and non-existing entries
"X-Taskcluster-Proxy-Temp-Scopes": "",
},
)
}
func testWithTempCreds(t *testing.T, test IntegrationTest, expectedStatusCode int) {
skipIfNoPermCreds(t)
tempScopes := []string{
"auth:azure-table-access:fakeaccount/DuMmYtAbLe",
"queue:define-task:win-provisioner/win2008-worker",
"queue:get-artifact:private/build/sources.xml",
"queue:route:tc-treeherder.mozilla-inbound.*",
"queue:route:tc-treeherder-stage.mozilla-inbound.*",
"queue:task-priority:high",
"test-worker:image:toastposter/pumpkin:0.5.6",
}
tempCredentials, err := permCredentials.CreateTemporaryCredentials(1*time.Hour, tempScopes...)
if err != nil {
t.Fatalf("Could not generate temp credentials")
}
res := test(t, tempCredentials)
checkStatusCode(
t,
res,
expectedStatusCode,
)
checkHeaders(
t,
res,
map[string]string{
"X-Taskcluster-Proxy-Version": version,
"X-Taskcluster-Proxy-Temp-Scopes": fmt.Sprintf("%s", tempScopes),
// N.B. the http library does not distinguish between header entries
// that have an empty "" value, and non-existing entries
"X-Taskcluster-Proxy-Perm-ClientId": "",
},
)
}
func checkHeaders(t *testing.T, res *httptest.ResponseRecorder, requiredHeaders map[string]string) {
for headerKey, expectedHeaderValue := range requiredHeaders {
actualHeaderValue := res.Header().Get(headerKey)
if actualHeaderValue != expectedHeaderValue {
// N.B. the http library does not distinguish between header
// entries that have an empty "" value, and non-existing entries
if expectedHeaderValue != "" {
t.Errorf("Expected header %q to be %q but it was %q", headerKey, expectedHeaderValue, actualHeaderValue)
t.Logf("Full headers: %q", res.Header())
} else {
t.Errorf("Expected header %q to not be present, or to be an empty string (\"\"), but it was %q", headerKey, actualHeaderValue)
}
}
}
}
func checkStatusCode(t *testing.T, res *httptest.ResponseRecorder, statusCode int) {
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Could not read response body: %v", err)
}
// make sure we get at least a few bytes of a response body...
// even http 303 should have some body, see
// https://tools.ietf.org/html/rfc7231#section-6.4.4
if len(respBody) < 20 {
t.Error("Expected a response body (at least 20 bytes), but get less (or none).")
t.Logf("Headers: %s", res.Header())
t.Logf("Response received:\n%s", string(respBody))
}
if res.Code != statusCode {
t.Errorf("Expected status code %v but got %v", statusCode, res.Code)
t.Logf("Headers: %s", res.Header())
t.Logf("Response received:\n%s", string(respBody))
}
}
func TestBewit(t *testing.T) {
test := func(t *testing.T, creds *tcclient.Credentials) *httptest.ResponseRecorder {
// Test setup
routes := Routes{
ConnectionData: tcclient.ConnectionData{
Credentials: creds,
},
}
req, err := http.NewRequest(
"POST",
"http://localhost:60024/bewit",
bytes.NewBufferString("https://queue.taskcluster.net/v1/task/DD1kmgFiRMWTjyiNoEJIMA/runs/0/artifacts/private%2Fbuild%2Fsources.xml"),
)
if err != nil {
log.Fatal(err)
}
res := httptest.NewRecorder()
// Function to test
routes.ServeHTTP(res, req)
// Validate results
bewitUrl := res.Header().Get("Location")
_, err = url.Parse(bewitUrl)
if err != nil {
t.Fatalf("Bewit URL returned is invalid: %q", bewitUrl)
}
resp, _, err := httpbackoff.Get(bewitUrl)
if err != nil {
t.Fatalf("Exception thrown:\n%s", err)
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Exception thrown:\n%s", err)
}
if len(respBody) != 18170 {
t.Logf("Response received:\n%s", string(respBody))
t.Fatalf("Expected response body to be 18170 bytes, but was %v bytes", len(respBody))
}
return res
}
testWithPermCreds(t, test, 303)
testWithTempCreds(t, test, 303)
}
func TestAuthorizationDelegate(t *testing.T) {
test := func(name string, scopes []string) IntegrationTest {
return func(t *testing.T, creds *tcclient.Credentials) *httptest.ResponseRecorder {
// Test setup
routes := Routes{
ConnectionData: tcclient.ConnectionData{
Authenticate: true,
Credentials: &tcclient.Credentials{
ClientId: creds.ClientId,
AccessToken: creds.AccessToken,
Certificate: creds.Certificate,
AuthorizedScopes: scopes,
},
},
}
// Requires scope "auth:azure-table-access:fakeaccount/DuMmYtAbLe"
req, err := http.NewRequest(
"GET",
fmt.Sprintf(
"http://localhost:60024/auth/v1/azure/%s/table/%s/read-write",
"fakeaccount",
"DuMmYtAbLe",
),
// Note: we don't set body to nil as a server http request
// cannot have a nil body. See:
// https://golang.org/pkg/net/http/#Request
new(bytes.Buffer),
)
if err != nil {
log.Fatal(err)
}
res := httptest.NewRecorder()
// Function to test
routes.ServeHTTP(res, req)
return res
}
}
testWithPermCreds(t, test("A", []string{"auth:azure-table-access:fakeaccount/DuMmYtAbLe"}), 404)
testWithTempCreds(t, test("B", []string{"auth:azure-table-access:fakeaccount/DuMmYtAbLe"}), 404)
testWithPermCreds(t, test("C", []string{"queue:get-artifact:private/build/sources.xml"}), 403)
testWithTempCreds(t, test("D", []string{"queue:get-artifact:private/build/sources.xml"}), 403)
}
func TestAPICallWithPayload(t *testing.T) {
test := func(t *testing.T, creds *tcclient.Credentials) *httptest.ResponseRecorder {
// Test setup
routes := Routes{
ConnectionData: tcclient.ConnectionData{
Authenticate: true,
Credentials: creds,
},
}
taskId := slugid.Nice()
taskGroupId := slugid.Nice()
created := time.Now()
deadline := created.AddDate(0, 0, 1)
expires := deadline
req, err := http.NewRequest(
"POST",
"http://localhost:60024/queue/v1/task/"+taskId+"/define",
bytes.NewBufferString(
`
{
"provisionerId": "win-provisioner",
"workerType": "win2008-worker",
"schedulerId": "go-test-test-scheduler",
"taskGroupId": "`+taskGroupId+`",
"routes": [
"tc-treeherder.mozilla-inbound.bcf29c305519d6e120b2e4d3b8aa33baaf5f0163",
"tc-treeherder-stage.mozilla-inbound.bcf29c305519d6e120b2e4d3b8aa33baaf5f0163"
],
"priority": "high",
"retries": 5,
"created": "`+tcclient.Time(created).String()+`",
"deadline": "`+tcclient.Time(deadline).String()+`",
"expires": "`+tcclient.Time(expires).String()+`",
"scopes": [
"test-worker:image:toastposter/pumpkin:0.5.6"
],
"payload": {
"features": {
"relengApiProxy": true
}
},
"metadata": {
"description": "Stuff",
"name": "[TC] Pete",
"owner": "pmoore@mozilla.com",
"source": "http://everywhere.com/"
},
"tags": {
"createdForUser": "cbook@mozilla.com"
},
"extra": {
"index": {
"rank": 12345
}
}
}
`,
),
)
if err != nil {
log.Fatal(err)
}
res := httptest.NewRecorder()
// Function to test
routes.ServeHTTP(res, req)
t.Logf("Created task https://queue.taskcluster.net/v1/task/%v", taskId)
return res
}
testWithPermCreds(t, test, 200)
testWithTempCreds(t, test, 200)
}
func TestNon200HasErrorBody(t *testing.T) {
test := func(t *testing.T, creds *tcclient.Credentials) *httptest.ResponseRecorder {
// Test setup
routes := Routes{
ConnectionData: tcclient.ConnectionData{
Authenticate: true,
Credentials: creds,
},
}
taskId := slugid.Nice()
req, err := http.NewRequest(
"POST",
"http://localhost:60024/queue/v1/task/"+taskId+"/define",
bytes.NewBufferString(
`{"comment": "Valid json so that we hit endpoint, but should not result in http 200"}`,
),
)
if err != nil {
log.Fatal(err)
}
res := httptest.NewRecorder()
// Function to test
routes.ServeHTTP(res, req)
// Validate results
return res
}
testWithPermCreds(t, test, 400)
testWithTempCreds(t, test, 400)
}
func TestOversteppedScopes(t *testing.T) {
test := func(t *testing.T, creds *tcclient.Credentials) *httptest.ResponseRecorder {
// Test setup
routes := Routes{
ConnectionData: tcclient.ConnectionData{
Authenticate: true,
Credentials: creds,
},
}
// This scope is not in the scopes of the temp credentials, which would
// happen if a task declares a scope that the provisioner does not
// grant.
routes.Credentials.AuthorizedScopes = []string{"secrets:get:garbage/pmoore/foo"}
req, err := http.NewRequest(
"GET",
"http://localhost:60024/secrets/v1/secret/garbage/pmoore/foo",
new(bytes.Buffer),
)
if err != nil {
log.Fatal(err)
}
res := httptest.NewRecorder()
// Function to test
routes.ServeHTTP(res, req)
// Validate results
checkHeaders(
t,
res,
map[string]string{
"X-Taskcluster-Endpoint": "https://secrets.taskcluster.net/v1/secret/garbage/pmoore/foo",
"X-Taskcluster-Authorized-Scopes": "[secrets:get:garbage/pmoore/foo]",
},
)
return res
}
testWithTempCreds(t, test, 500)
}
func TestBadCredsReturns500(t *testing.T) {
routes := Routes{
ConnectionData: tcclient.ConnectionData{
Authenticate: true,
Credentials: &tcclient.Credentials{
ClientId: "abc",
AccessToken: "def",
Certificate: "ghi", // baaaad certificate
},
},
}
req, err := http.NewRequest(
"GET",
"http://localhost:60024/secrets/v1/secret/garbage/pmoore/foo",
new(bytes.Buffer),
)
if err != nil {
log.Fatal(err)
}
res := httptest.NewRecorder()
// Function to test
routes.ServeHTTP(res, req)
// Validate results
checkStatusCode(t, res, 500)
}