auth

Paddy 2015-01-10 Parent:c03b5eb3179e Child:fa8ee6a4507c

113:5bd46746b809 Go to Latest

auth/client_test.go

Let's test our verifyClient function. C'mon, it'll be fun! Add a function that tests the verifyClient function to our unit test suite. Basically, make sure that all the conceivable types of input have the right logic flow for what a "valid client" is. Also leave a note in client.go that makes it clear that public clients _should not be issued secrets in the first place_, because a public client that is issued a secret and specifies its client ID using the `client_id` POST body format will be told that it is not a valid client. While there are ways around this, the spec clearly states that non-confidential clients are not supposed to be issued secrets, so this seems like a nice way to conform to the spec or break trying.

History
1 package auth
3 import (
4 "bytes"
5 "fmt"
6 "io/ioutil"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "sort"
11 "strings"
12 "testing"
13 "time"
15 "code.secondbit.org/uuid.hg"
16 )
18 const (
19 clientChangeSecret = 1 << iota
20 clientChangeOwnerID
21 clientChangeName
22 clientChangeLogo
23 clientChangeWebsite
24 )
26 var clientStores = []clientStore{NewMemstore()}
28 func compareClients(client1, client2 Client) (success bool, field string, val1, val2 interface{}) {
29 if !client1.ID.Equal(client2.ID) {
30 return false, "ID", client1.ID, client2.ID
31 }
32 if client1.Secret != client2.Secret {
33 return false, "secret", client1.Secret, client2.Secret
34 }
35 if !client1.OwnerID.Equal(client2.OwnerID) {
36 return false, "owner ID", client1.OwnerID, client2.OwnerID
37 }
38 if client1.Name != client2.Name {
39 return false, "name", client1.Name, client2.Name
40 }
41 if client1.Logo != client2.Logo {
42 return false, "logo", client1.Logo, client2.Logo
43 }
44 if client1.Website != client2.Website {
45 return false, "website", client1.Website, client2.Website
46 }
47 if client1.Type != client2.Type {
48 return false, "type", client1.Type, client2.Type
49 }
50 return true, "", nil, nil
51 }
53 func compareEndpoints(endpoint1, endpoint2 Endpoint) (success bool, field string, val1, val2 interface{}) {
54 if !endpoint1.ID.Equal(endpoint2.ID) {
55 return false, "ID", endpoint1.ID, endpoint2.ID
56 }
57 if !endpoint1.ClientID.Equal(endpoint2.ClientID) {
58 return false, "OwnerID", endpoint1.ClientID, endpoint2.ClientID
59 }
60 if !endpoint1.Added.Equal(endpoint2.Added) {
61 return false, "Added", endpoint1.Added, endpoint2.Added
62 }
63 if endpoint1.URI.String() != endpoint2.URI.String() {
64 return false, "URI", endpoint1.URI, endpoint2.URI
65 }
66 return true, "", nil, nil
67 }
69 func TestClientStoreSuccess(t *testing.T) {
70 t.Parallel()
71 client := Client{
72 ID: uuid.NewID(),
73 Secret: "secret",
74 OwnerID: uuid.NewID(),
75 Name: "name",
76 Logo: "logo",
77 Website: "website",
78 }
79 for _, store := range clientStores {
80 err := store.saveClient(client)
81 if err != nil {
82 t.Fatalf("Error saving client to %T: %s", store, err)
83 }
84 err = store.saveClient(client)
85 if err != ErrClientAlreadyExists {
86 t.Fatalf("Expected ErrClientAlreadyExists, got %v from %T", err, store)
87 }
88 retrieved, err := store.getClient(client.ID)
89 if err != nil {
90 t.Fatalf("Error retrieving client from %T: %s", store, err)
91 }
92 success, field, expectation, result := compareClients(client, retrieved)
93 if !success {
94 t.Fatalf("Expected field %s to be %v, but %T returned %v", field, expectation, store, result)
95 }
96 clients, err := store.listClientsByOwner(client.OwnerID, 25, 0)
97 if err != nil {
98 t.Fatalf("Error retrieving clients by owner from %T: %s", store, err)
99 }
100 if len(clients) != 1 {
101 t.Fatalf("Expected 1 client in response from %T, got %+v", store, clients)
102 }
103 success, field, expectation, result = compareClients(client, clients[0])
104 if !success {
105 t.Fatalf("Expected field %s to be %v, but %T returned %v", field, expectation, store, result)
106 }
107 err = store.deleteClient(client.ID)
108 if err != nil {
109 t.Fatalf("Error deleting client from %T: %s", store, err)
110 }
111 err = store.deleteClient(client.ID)
112 if err != ErrClientNotFound {
113 t.Fatalf("Expected ErrClientNotFound, got %s from %T", err, store)
114 }
115 retrieved, err = store.getClient(client.ID)
116 if err != ErrClientNotFound {
117 t.Fatalf("Expected ErrClientNotFound from %T, got %+v and %s", store, retrieved, err)
118 }
119 clients, err = store.listClientsByOwner(client.OwnerID, 25, 0)
120 if err != nil {
121 t.Fatalf("Error listing clients by owner from %T: %s", store, err)
122 }
123 if len(clients) != 0 {
124 t.Fatalf("Expected 0 clients in response from %T, got %+v", store, clients)
125 }
126 }
127 }
129 func TestEndpointStoreSuccess(t *testing.T) {
130 t.Parallel()
131 client := Client{
132 ID: uuid.NewID(),
133 Secret: "secret",
134 OwnerID: uuid.NewID(),
135 Name: "name",
136 Logo: "logo",
137 Website: "website",
138 }
139 uri1, _ := url.Parse("https://www.example.com/")
140 uri2, _ := url.Parse("https://www.example.com/my/full/path")
141 endpoint1 := Endpoint{
142 ID: uuid.NewID(),
143 ClientID: client.ID,
144 Added: time.Now(),
145 URI: *uri1,
146 }
147 endpoint2 := Endpoint{
148 ID: uuid.NewID(),
149 ClientID: client.ID,
150 Added: time.Now(),
151 URI: *uri2,
152 }
153 for _, store := range clientStores {
154 err := store.saveClient(client)
155 if err != nil {
156 t.Fatalf("Error saving client to %T: %s", store, err)
157 }
158 err = store.addEndpoint(client.ID, endpoint1)
159 if err != nil {
160 t.Fatalf("Error adding endpoint to client in %T: %s", store, err)
161 }
162 endpoints, err := store.listEndpoints(client.ID, 10, 0)
163 if err != nil {
164 t.Fatalf("Error retrieving endpoints from %T: %s", store, err)
165 }
166 if len(endpoints) != 1 {
167 t.Fatalf("Expected %d endpoints, got %+v from %T", 1, endpoints, store)
168 }
169 success, field, expectation, result := compareEndpoints(endpoint1, endpoints[0])
170 if !success {
171 t.Fatalf("Expected field %s to be %v, but %T returned %v", field, expectation, store, result)
172 }
173 err = store.addEndpoint(client.ID, endpoint2)
174 if err != nil {
175 t.Fatalf("Error adding endpoint to client in %T: %s", store, err)
176 }
177 endpoints, err = store.listEndpoints(client.ID, 10, 0)
178 if err != nil {
179 t.Fatalf("Error retrieving endpoints from %T: %s", store, err)
180 }
181 if len(endpoints) != 2 {
182 t.Fatalf("Expected %d endpoints, got %+v from %T", 2, endpoints, store)
183 }
184 sortedEnd := sortedEndpoints(endpoints)
185 sort.Sort(sortedEnd)
186 endpoints = []Endpoint(sortedEnd)
187 success, field, expectation, result = compareEndpoints(endpoint1, endpoints[0])
188 if !success {
189 t.Fatalf("Expected field %s to be %v, but %T returned %v", field, expectation, store, result)
190 }
191 success, field, expectation, result = compareEndpoints(endpoint2, endpoints[1])
192 if !success {
193 t.Fatalf("Expected field %s to be %v, but %T returned %v", field, expectation, store, result)
194 }
195 err = store.removeEndpoint(client.ID, endpoint1.ID)
196 if err != nil {
197 t.Fatalf("Error removing endpoint from client in %T: %s", store, err)
198 }
199 endpoints, err = store.listEndpoints(client.ID, 10, 0)
200 if err != nil {
201 t.Fatalf("Error listing endpoints in %T: %s", store, err)
202 }
203 if len(endpoints) != 1 {
204 t.Fatalf("Expected %d endpoints, got %+v from %T", 1, endpoints, store)
205 }
206 success, field, expectation, result = compareEndpoints(endpoint2, endpoints[0])
207 if !success {
208 t.Fatalf("Expected field %s to be %v, but %T returned %v", field, expectation, store, result)
209 }
210 err = store.removeEndpoint(client.ID, endpoint2.ID)
211 if err != nil {
212 t.Fatalf("Error removing endpoint from client in %T: %s", store, err)
213 }
214 endpoints, err = store.listEndpoints(client.ID, 10, 0)
215 if err != nil {
216 t.Fatalf("Error listing endpoints in %T: %s", store, err)
217 }
218 if len(endpoints) != 0 {
219 t.Fatalf("Expected %d endpoints, got %+v from %T", 0, endpoints, store)
220 }
221 }
222 }
224 func TestClientUpdates(t *testing.T) {
225 t.Parallel()
226 variations := 1 << 5
227 client := Client{
228 ID: uuid.NewID(),
229 Secret: "secret",
230 OwnerID: uuid.NewID(),
231 Name: "name",
232 Logo: "logo",
233 Website: "website",
234 }
235 for i := 0; i < variations; i++ {
236 var secret, name, logo, website string
237 change := ClientChange{}
238 expectation := client
239 result := client
240 if i&clientChangeSecret != 0 {
241 secret = fmt.Sprintf("secret-%d", i)
242 change.Secret = &secret
243 expectation.Secret = secret
244 }
245 if i&clientChangeOwnerID != 0 {
246 change.OwnerID = uuid.NewID()
247 expectation.OwnerID = change.OwnerID
248 }
249 if i&clientChangeName != 0 {
250 name = fmt.Sprintf("name-%d", i)
251 change.Name = &name
252 expectation.Name = name
253 }
254 if i&clientChangeLogo != 0 {
255 logo = fmt.Sprintf("logo-%d", i)
256 change.Logo = &logo
257 expectation.Logo = logo
258 }
259 if i&clientChangeWebsite != 0 {
260 website = fmt.Sprintf("website-%d", i)
261 change.Website = &website
262 expectation.Website = website
263 }
264 result.ApplyChange(change)
265 match, field, expected, got := compareClients(expectation, result)
266 if !match {
267 t.Fatalf("Expected field `%s` to be `%v`, got `%v`", field, expected, got)
268 }
269 for _, store := range clientStores {
270 err := store.saveClient(client)
271 if err != nil {
272 t.Fatalf("Error saving client in %T: %s", store, err)
273 }
274 err = store.updateClient(client.ID, change)
275 if err != nil {
276 t.Fatalf("Error updating client in %T: %s", store, err)
277 }
278 retrieved, err := store.getClient(client.ID)
279 if err != nil {
280 t.Fatalf("Error getting profile from %T: %s", store, err)
281 }
282 match, field, expected, got = compareClients(expectation, retrieved)
283 if !match {
284 t.Fatalf("Expected field `%s` to be `%v`, got `%v` from %T", field, expected, got, store)
285 }
286 err = store.deleteClient(client.ID)
287 if err != nil {
288 t.Fatalf("Error deleting client from %T: %s", store, err)
289 }
290 err = store.updateClient(client.ID, change)
291 if err != ErrClientNotFound {
292 t.Fatalf("Expected ErrClientNotFound, got %v from %T", err, store)
293 }
294 }
295 }
296 }
298 func TestClientEndpointChecks(t *testing.T) {
299 t.Parallel()
300 client := Client{
301 ID: uuid.NewID(),
302 Secret: "secret",
303 OwnerID: uuid.NewID(),
304 Name: "name",
305 Logo: "logo",
306 Website: "website",
307 }
308 uri1, _ := url.Parse("https://www.example.com/first")
309 uri2, _ := url.Parse("https://www.example.com/my/full/path")
310 endpoint1 := Endpoint{
311 ID: uuid.NewID(),
312 ClientID: client.ID,
313 Added: time.Now(),
314 URI: *uri1,
315 }
316 endpoint2 := Endpoint{
317 ID: uuid.NewID(),
318 ClientID: client.ID,
319 Added: time.Now(),
320 URI: *uri2,
321 }
322 candidates := map[string]bool{
323 "https://www.example.com/": false,
324 "https://www.example.com/first": true,
325 "https://www.example.com/first/extra/path": false,
326 "https://www.example.com/my": false,
327 "https://www.example.com/my/full/path": true,
328 }
329 for _, store := range clientStores {
330 err := store.saveClient(client)
331 if err != nil {
332 t.Fatalf("Error saving client in %T: %s", store, err)
333 }
334 err = store.addEndpoint(client.ID, endpoint1)
335 if err != nil {
336 t.Fatalf("Error saving endpoint in %T: %s", store, err)
337 }
338 err = store.addEndpoint(client.ID, endpoint2)
339 if err != nil {
340 t.Fatalf("Error saving endpoint in %T: %s", store, err)
341 }
342 for candidate, expectation := range candidates {
343 result, err := store.checkEndpoint(client.ID, candidate)
344 if err != nil {
345 t.Fatalf("Error checking endpoint %s in %T: %s", candidate, store, err)
346 }
347 if result != expectation {
348 expectStr := "no"
349 resultStr := "a"
350 if expectation {
351 expectStr = "a"
352 resultStr = "no"
353 }
354 t.Errorf("Expected %s match for %s in %T, got %s match", expectStr, candidate, store, resultStr)
355 }
356 }
357 }
358 }
360 func TestClientEndpointChecksStrict(t *testing.T) {
361 t.Parallel()
362 client := Client{
363 ID: uuid.NewID(),
364 Secret: "secret",
365 OwnerID: uuid.NewID(),
366 Name: "name",
367 Logo: "logo",
368 Website: "website",
369 }
370 uri1, _ := url.Parse("https://www.example.com/first")
371 uri2, _ := url.Parse("https://www.example.com/my/full/path")
372 endpoint1 := Endpoint{
373 ID: uuid.NewID(),
374 ClientID: client.ID,
375 Added: time.Now(),
376 URI: *uri1,
377 }
378 endpoint2 := Endpoint{
379 ID: uuid.NewID(),
380 ClientID: client.ID,
381 Added: time.Now(),
382 URI: *uri2,
383 }
384 candidates := map[string]bool{
385 "https://www.example.com/": false,
386 "https://www.example.com/first": true,
387 "https://www.example.com/first/extra/path": false,
388 "https://www.example.com/my": false,
389 "https://www.example.com/my/full/path": true,
390 }
391 for _, store := range clientStores {
392 err := store.saveClient(client)
393 if err != nil {
394 t.Fatalf("Error saving client in %T: %s", store, err)
395 }
396 err = store.addEndpoint(client.ID, endpoint1)
397 if err != nil {
398 t.Fatalf("Error saving endpoint in %T: %s", store, err)
399 }
400 err = store.addEndpoint(client.ID, endpoint2)
401 if err != nil {
402 t.Fatalf("Error saving endpoint in %T: %s", store, err)
403 }
404 for candidate, expectation := range candidates {
405 result, err := store.checkEndpoint(client.ID, candidate)
406 if err != nil {
407 t.Fatalf("Error checking endpoint %s in %T: %s", candidate, store, err)
408 }
409 if result != expectation {
410 expectStr := "no"
411 resultStr := "a"
412 if expectation {
413 expectStr = "a"
414 resultStr = "no"
415 }
416 t.Errorf("Expected %s match for %s in %T, got %s match", expectStr, candidate, store, resultStr)
417 }
418 }
419 }
420 }
422 func TestClientChangeValidation(t *testing.T) {
423 t.Parallel()
424 change := ClientChange{}
425 if err := change.Validate(); err != ErrEmptyChange {
426 t.Errorf("Expected %s to give an error of %s, gave %s", "empty change", ErrEmptyChange, err)
427 }
428 names := map[string]error{
429 "a": ErrClientNameTooShort,
430 "ab": nil,
431 "abc": nil,
432 "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq": ErrClientNameTooLong,
433 }
434 for name, expectation := range names {
435 change = ClientChange{Name: &name}
436 if err := change.Validate(); err != expectation {
437 t.Errorf("Expected %s to give an error of %s, gave %s", name, expectation, err)
438 }
439 }
440 longPath := ""
441 for i := 0; i < 1025; i++ {
442 longPath = fmt.Sprintf("%s%d", longPath, i)
443 }
444 logos := map[string]error{
445 "https://www.example.com/" + longPath: ErrClientLogoTooLong,
446 "https://www.example.com/ab": nil,
447 "www.example.com/ab": ErrClientLogoNotURL,
448 "test": ErrClientLogoNotURL,
449 "": nil,
450 }
451 for logo, expectation := range logos {
452 change = ClientChange{Logo: &logo}
453 if err := change.Validate(); err != expectation {
454 t.Errorf("Expected %s to give an error of %s, gave %s", logo, expectation, err)
455 }
456 }
457 websites := map[string]error{
458 "https://www.example.com/" + longPath: ErrClientWebsiteTooLong,
459 "https://www.example.com/ab": nil,
460 "www.example.com/ab": ErrClientWebsiteNotURL,
461 "test": ErrClientWebsiteNotURL,
462 "": nil,
463 }
464 for website, expectation := range websites {
465 change = ClientChange{Website: &website}
466 if err := change.Validate(); err != expectation {
467 t.Errorf("Expected %s to give an error of %s, gave %s", website, expectation, err)
468 }
469 }
470 }
472 func TestVerifyClient(t *testing.T) {
473 t.Parallel()
474 memstore := NewMemstore()
475 context := Context{
476 clients: memstore,
477 }
478 client := Client{
479 ID: uuid.NewID(),
480 Secret: "super secret!",
481 OwnerID: uuid.NewID(),
482 Name: "My test client",
483 Logo: "https://secondbit.org/logo.png",
484 Website: "https://secondbit.org/",
485 Type: "confidential",
486 }
487 err := context.SaveClient(client)
488 if err != nil {
489 t.Fatal("Could not save client:", err)
490 }
491 publicClient := Client{
492 ID: uuid.NewID(),
493 Secret: "",
494 OwnerID: uuid.NewID(),
495 Name: "A public client",
496 Logo: "https://secondbit.org/logo.png",
497 Website: "https://secondbit.org/",
498 Type: "public",
499 }
500 err = context.SaveClient(publicClient)
501 if err != nil {
502 t.Fatal("Could not save client:", err)
503 }
505 // verifyClient with no auth header, no public clients
506 w := httptest.NewRecorder()
507 r, err := http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
508 if err != nil {
509 t.Fatal("Can't build request:", err)
510 }
511 resp, success := verifyClient(w, r, false, context)
512 if success {
513 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
514 }
515 if resp != nil {
516 t.Error("Expected nil client ID, got", resp)
517 }
518 if w.Code != http.StatusBadRequest {
519 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
520 }
521 expectedBody := `{"error":"unauthorized_client"}`
522 if expectedBody != strings.TrimSpace(w.Body.String()) {
523 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
524 }
526 // verifyClient with no auth header, public clients, empty client_id
527 w = httptest.NewRecorder()
528 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
529 if err != nil {
530 t.Fatal("Can't build request:", err)
531 }
532 resp, success = verifyClient(w, r, true, context)
533 if success {
534 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
535 }
536 if resp != nil {
537 t.Error("Expected nil client ID, got", resp)
538 }
539 if w.Code != http.StatusUnauthorized {
540 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
541 }
542 expectedBody = `{"error":"invalid_client"}`
543 if expectedBody != strings.TrimSpace(w.Body.String()) {
544 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
545 }
547 // verifyClient with auth header, no public clients, empty client id
548 w = httptest.NewRecorder()
549 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
550 if err != nil {
551 t.Fatal("Can't build request:", err)
552 }
553 r.SetBasicAuth("", "no client ID set")
554 resp, success = verifyClient(w, r, false, context)
555 if success {
556 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
557 }
558 if resp != nil {
559 t.Error("Expected nil client ID, got", resp)
560 }
561 if w.Code != http.StatusUnauthorized {
562 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
563 }
564 expectedBody = `{"error":"invalid_client"}`
565 if expectedBody != strings.TrimSpace(w.Body.String()) {
566 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
567 }
568 if w.Header().Get("WWW-Authenticate") != "Basic" {
569 t.Errorf(`Expected header WWW-Authenticate to be set to "Basic", got "%s"`, w.Header().Get("WWW-Authenticate"))
570 }
572 // verifyClient with auth header, public clients, empty client id
573 w = httptest.NewRecorder()
574 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
575 if err != nil {
576 t.Fatal("Can't build request:", err)
577 }
578 r.SetBasicAuth("", "no client ID set")
579 resp, success = verifyClient(w, r, true, context)
580 if success {
581 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
582 }
583 if resp != nil {
584 t.Error("Expected nil client ID, got", resp)
585 }
586 if w.Code != http.StatusUnauthorized {
587 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
588 }
589 expectedBody = `{"error":"invalid_client"}`
590 if expectedBody != strings.TrimSpace(w.Body.String()) {
591 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
592 }
593 if w.Header().Get("WWW-Authenticate") != "Basic" {
594 t.Errorf(`Expected header WWW-Authenticate to be set to "Basic", got "%s"`, w.Header().Get("WWW-Authenticate"))
595 }
597 // verifyClient with auth header, no public clients, invalid client ID
598 w = httptest.NewRecorder()
599 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
600 if err != nil {
601 t.Fatal("Can't build request:", err)
602 }
603 r.SetBasicAuth("not an actual id", "invalid client ID set")
604 resp, success = verifyClient(w, r, false, context)
605 if success {
606 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
607 }
608 if resp != nil {
609 t.Error("Expected nil client ID, got", resp)
610 }
611 if w.Code != http.StatusUnauthorized {
612 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
613 }
614 expectedBody = `{"error":"invalid_client"}`
615 if expectedBody != strings.TrimSpace(w.Body.String()) {
616 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
617 }
618 if w.Header().Get("WWW-Authenticate") != "Basic" {
619 t.Errorf(`Expected header WWW-Authenticate to be set to "Basic", got "%s"`, w.Header().Get("WWW-Authenticate"))
620 }
622 // verifyClient with auth header, public clients, invalid client ID
623 w = httptest.NewRecorder()
624 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
625 if err != nil {
626 t.Fatal("Can't build request:", err)
627 }
628 r.SetBasicAuth("not an actual id", "invalid client ID set")
629 resp, success = verifyClient(w, r, true, context)
630 if success {
631 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
632 }
633 if resp != nil {
634 t.Error("Expected nil client ID, got", resp)
635 }
636 if w.Code != http.StatusUnauthorized {
637 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
638 }
639 expectedBody = `{"error":"invalid_client"}`
640 if expectedBody != strings.TrimSpace(w.Body.String()) {
641 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
642 }
643 if w.Header().Get("WWW-Authenticate") != "Basic" {
644 t.Errorf(`Expected header WWW-Authenticate to be set to "Basic", got "%s"`, w.Header().Get("WWW-Authenticate"))
645 }
647 // verifyClient with auth header, no public clients, client ID valid but not in clientStore
648 w = httptest.NewRecorder()
649 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
650 if err != nil {
651 t.Fatal("Can't build request:", err)
652 }
653 r.SetBasicAuth(uuid.NewID().String(), "non existent client ID set")
654 resp, success = verifyClient(w, r, false, context)
655 if success {
656 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
657 }
658 if resp != nil {
659 t.Error("Expected nil client ID, got", resp)
660 }
661 if w.Code != http.StatusUnauthorized {
662 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
663 }
664 expectedBody = `{"error":"invalid_client"}`
665 if expectedBody != strings.TrimSpace(w.Body.String()) {
666 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
667 }
668 if w.Header().Get("WWW-Authenticate") != "Basic" {
669 t.Errorf(`Expected header WWW-Authenticate to be set to "Basic", got "%s"`, w.Header().Get("WWW-Authenticate"))
670 }
672 // verifyClient with auth header, public clients, client ID valid but not in clientStore
673 w = httptest.NewRecorder()
674 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
675 if err != nil {
676 t.Fatal("Can't build request:", err)
677 }
678 r.SetBasicAuth(uuid.NewID().String(), "non existent client ID set")
679 resp, success = verifyClient(w, r, true, context)
680 if success {
681 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
682 }
683 if resp != nil {
684 t.Error("Expected nil client ID, got", resp)
685 }
686 if w.Code != http.StatusUnauthorized {
687 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
688 }
689 expectedBody = `{"error":"invalid_client"}`
690 if expectedBody != strings.TrimSpace(w.Body.String()) {
691 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
692 }
693 if w.Header().Get("WWW-Authenticate") != "Basic" {
694 t.Errorf(`Expected header WWW-Authenticate to be set to "Basic", got "%s"`, w.Header().Get("WWW-Authenticate"))
695 }
697 // verifyClient with auth header, no public clients, client secret wrong
698 w = httptest.NewRecorder()
699 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
700 if err != nil {
701 t.Fatal("Can't build request:", err)
702 }
703 r.SetBasicAuth(client.ID.String(), "not actually the secret")
704 resp, success = verifyClient(w, r, false, context)
705 if success {
706 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
707 }
708 if resp != nil {
709 t.Error("Expected nil client ID, got", resp)
710 }
711 if w.Code != http.StatusUnauthorized {
712 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
713 }
714 expectedBody = `{"error":"invalid_client"}`
715 if expectedBody != strings.TrimSpace(w.Body.String()) {
716 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
717 }
718 if w.Header().Get("WWW-Authenticate") != "Basic" {
719 t.Errorf(`Expected header WWW-Authenticate to be set to "Basic", got "%s"`, w.Header().Get("WWW-Authenticate"))
720 }
722 // verifyClient with auth header, public clients, client secret wrong
723 w = httptest.NewRecorder()
724 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
725 if err != nil {
726 t.Fatal("Can't build request:", err)
727 }
728 r.SetBasicAuth(client.ID.String(), "not actually the secret")
729 resp, success = verifyClient(w, r, true, context)
730 if success {
731 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
732 }
733 if resp != nil {
734 t.Error("Expected nil client ID, got", resp)
735 }
736 if w.Code != http.StatusUnauthorized {
737 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
738 }
739 expectedBody = `{"error":"invalid_client"}`
740 if expectedBody != strings.TrimSpace(w.Body.String()) {
741 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
742 }
743 if w.Header().Get("WWW-Authenticate") != "Basic" {
744 t.Errorf(`Expected header WWW-Authenticate to be set to "Basic", got "%s"`, w.Header().Get("WWW-Authenticate"))
745 }
747 // verifyClient with no auth header, public clients, invalid client_id post form value
748 w = httptest.NewRecorder()
749 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
750 if err != nil {
751 t.Fatal("Can't build request:", err)
752 }
753 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
754 params := url.Values{}
755 params.Set("client_id", "not an actual id")
756 body := bytes.NewBufferString(params.Encode())
757 r.Body = ioutil.NopCloser(body)
758 resp, success = verifyClient(w, r, true, context)
759 if success {
760 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
761 }
762 if resp != nil {
763 t.Error("Expected nil client ID, got", resp)
764 }
765 if w.Code != http.StatusUnauthorized {
766 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
767 }
768 expectedBody = `{"error":"invalid_client"}`
769 if expectedBody != strings.TrimSpace(w.Body.String()) {
770 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
771 }
773 // verifyClient with no auth header, public clients, client_id valid but not in clientStore
774 w = httptest.NewRecorder()
775 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
776 if err != nil {
777 t.Fatal("Can't build request:", err)
778 }
779 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
780 params = url.Values{}
781 params.Set("client_id", uuid.NewID().String())
782 body = bytes.NewBufferString(params.Encode())
783 r.Body = ioutil.NopCloser(body)
784 resp, success = verifyClient(w, r, true, context)
785 if success {
786 t.Error("Expected verification to fail, but succeeded with client ID:", resp)
787 }
788 if resp != nil {
789 t.Error("Expected nil client ID, got", resp)
790 }
791 if w.Code != http.StatusUnauthorized {
792 t.Errorf("Expected status code of %d, got %d", http.StatusBadRequest, w.Code)
793 }
794 expectedBody = `{"error":"invalid_client"}`
795 if expectedBody != strings.TrimSpace(w.Body.String()) {
796 t.Errorf("Expected body of `%s`, got `%s`", expectedBody, strings.TrimSpace(w.Body.String()))
797 }
799 // verifyClient with auth header, public clients, valid client_id and secret
800 w = httptest.NewRecorder()
801 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
802 if err != nil {
803 t.Fatal("Can't build request:", err)
804 }
805 r.SetBasicAuth(client.ID.String(), client.Secret)
806 resp, success = verifyClient(w, r, true, context)
807 if !success {
808 t.Error("Expected verification to succeed, but it failed")
809 }
810 if !client.ID.Equal(resp) {
811 t.Errorf("Expected client ID to be %s, got %s", client.ID, resp)
812 }
813 if w.Code != http.StatusOK {
814 t.Errorf("Expected status code of %d, got %d", http.StatusOK, w.Code)
815 }
816 if w.Body.String() != "" {
817 t.Errorf(`Expected empty body, got "%s"`, w.Body.String())
818 }
820 // verifyClient with auth header, no public clients, valid client_id and secret
821 w = httptest.NewRecorder()
822 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
823 if err != nil {
824 t.Fatal("Can't build request:", err)
825 }
826 r.SetBasicAuth(client.ID.String(), client.Secret)
827 resp, success = verifyClient(w, r, true, context)
828 if !success {
829 t.Error("Expected verification to succeed, but it failed")
830 }
831 if !client.ID.Equal(resp) {
832 t.Errorf("Expected client ID to be %s, got %s", client.ID, resp)
833 }
834 if w.Code != http.StatusOK {
835 t.Errorf("Expected status code of %d, got %d", http.StatusOK, w.Code)
836 }
837 if w.Body.String() != "" {
838 t.Errorf(`Expected empty body, got "%s"`, w.Body.String())
839 }
841 // verifyClient with no auth header, public clients, valid client_id and secret
842 w = httptest.NewRecorder()
843 r, err = http.NewRequest("POST", "https://test.auth.secondbit.org/oauth2/grant", nil)
844 if err != nil {
845 t.Fatal("Can't build request:", err)
846 }
847 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
848 params = url.Values{}
849 params.Set("client_id", publicClient.ID.String())
850 body = bytes.NewBufferString(params.Encode())
851 r.Body = ioutil.NopCloser(body)
852 resp, success = verifyClient(w, r, true, context)
853 if !success {
854 t.Error("Expected verification to succeed, but it failed")
855 }
856 if !publicClient.ID.Equal(resp) {
857 t.Errorf("Expected client ID to be %s, got %s", publicClient.ID, resp)
858 }
859 if w.Code != http.StatusOK {
860 t.Errorf("Expected status code of %d, got %d", http.StatusOK, w.Code)
861 }
862 if w.Body.String() != "" {
863 t.Errorf(`Expected empty body, got "%s"`, w.Body.String())
864 }
865 }