auth

Paddy 2014-12-06 Parent:0a6e3f14b054 Child:1dc4e152e3b0

84:4cb65cf90217 Go to Latest

auth/oauth2_test.go

Start supporting our pluggable grant_type. Define GrantType as a way to bundle information that can be used to validate requests based on their grant_type parameter. Move our validation of the authorization_code grant_type out of GetTokenHandler and into its own function. Define RegisterGrantType as a way to register new grant_type bundles and associate them with the string passed to grant_type. This enables other packages to define RegisterGrantType in their init() functions and plug in new grant types without forking this code. Implement RegisterGrantType for our authorization_code grant type.

History
paddy@52 1 package auth
paddy@52 2
paddy@52 3 import (
paddy@66 4 "bytes"
paddy@81 5 "encoding/json"
paddy@52 6 "html/template"
paddy@66 7 "io/ioutil"
paddy@52 8 "net/http"
paddy@52 9 "net/http/httptest"
paddy@53 10 "net/url"
paddy@52 11 "testing"
paddy@56 12 "time"
paddy@56 13
paddy@56 14 "code.secondbit.org/uuid"
paddy@52 15 )
paddy@52 16
paddy@53 17 const (
paddy@53 18 scopeSet = 1 << iota
paddy@53 19 stateSet
paddy@53 20 uriSet
paddy@53 21 )
paddy@53 22
paddy@65 23 func stripParam(param string, u *url.URL) {
paddy@65 24 q := u.Query()
paddy@65 25 q.Del(param)
paddy@65 26 u.RawQuery = q.Encode()
paddy@65 27 }
paddy@65 28
paddy@52 29 func TestGetGrantCodeSuccess(t *testing.T) {
paddy@52 30 t.Parallel()
paddy@52 31 store := NewMemstore()
paddy@52 32 testContext := Context{
paddy@52 33 template: template.Must(template.New(getGrantTemplateName).Parse("Get auth grant")),
paddy@52 34 clients: store,
paddy@52 35 grants: store,
paddy@52 36 profiles: store,
paddy@52 37 tokens: store,
paddy@77 38 sessions: store,
paddy@52 39 }
paddy@56 40 client := Client{
paddy@56 41 ID: uuid.NewID(),
paddy@56 42 Secret: "super secret!",
paddy@56 43 OwnerID: uuid.NewID(),
paddy@56 44 Name: "My test client",
paddy@56 45 Logo: "https://secondbit.org/logo.png",
paddy@56 46 Website: "https://secondbit.org",
paddy@56 47 Type: "public",
paddy@56 48 }
paddy@56 49 uri, err := url.Parse("https://test.secondbit.org/redirect")
paddy@56 50 if err != nil {
paddy@56 51 t.Fatal("Can't parse URL:", err)
paddy@56 52 }
paddy@56 53 endpoint := Endpoint{
paddy@56 54 ID: uuid.NewID(),
paddy@56 55 ClientID: client.ID,
paddy@56 56 URI: *uri,
paddy@56 57 Added: time.Now(),
paddy@56 58 }
paddy@56 59 err = testContext.SaveClient(client)
paddy@56 60 if err != nil {
paddy@56 61 t.Fatal("Can't store client:", err)
paddy@56 62 }
paddy@56 63 err = testContext.AddEndpoint(client.ID, endpoint)
paddy@56 64 if err != nil {
paddy@56 65 t.Fatal("Can't store endpoint:", err)
paddy@56 66 }
paddy@77 67 session := Session{
paddy@77 68 ID: "testsession",
paddy@77 69 Active: true,
paddy@77 70 }
paddy@77 71 err = testContext.CreateSession(session)
paddy@77 72 if err != nil {
paddy@77 73 t.Fatal("Can't store session:", err)
paddy@77 74 }
paddy@52 75 req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
paddy@52 76 if err != nil {
paddy@52 77 t.Fatal("Can't build request:", err)
paddy@52 78 }
paddy@77 79 cookie := &http.Cookie{
paddy@77 80 Name: authCookieName,
paddy@77 81 Value: session.ID,
paddy@77 82 }
paddy@77 83 req.AddCookie(cookie)
paddy@58 84 for i := 0; i < 1<<3; i++ {
paddy@53 85 w := httptest.NewRecorder()
paddy@53 86 params := url.Values{}
paddy@53 87 // see OAuth 2.0 spec, section 4.1.1
paddy@53 88 params.Set("response_type", "code")
paddy@56 89 params.Set("client_id", client.ID.String())
paddy@53 90 if i&uriSet != 0 {
paddy@58 91 params.Set("redirect_uri", endpoint.URI.String())
paddy@53 92 }
paddy@53 93 if i&scopeSet != 0 {
paddy@53 94 params.Set("scope", "testscope")
paddy@53 95 }
paddy@53 96 if i&stateSet != 0 {
paddy@53 97 params.Set("state", "my super secure state string")
paddy@53 98 }
paddy@53 99 req.URL.RawQuery = params.Encode()
paddy@66 100 req.Method = "GET"
paddy@66 101 req.Body = nil
paddy@66 102 req.Header.Del("Content-Type")
paddy@53 103 GetGrantHandler(w, req, testContext)
paddy@53 104 if w.Code != http.StatusOK {
paddy@53 105 t.Errorf("Expected status code to be %d, got %d for %s", http.StatusOK, w.Code, req.URL.String())
paddy@53 106 }
paddy@53 107 if w.Body.String() != "Get auth grant" {
paddy@53 108 t.Errorf("Expected body to be `%s`, got `%s` for %s", "Get auth grant", w.Body.String(), req.URL.String())
paddy@53 109 }
paddy@66 110 req.Method = "POST"
paddy@66 111 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
paddy@66 112 w = httptest.NewRecorder()
paddy@66 113 data := url.Values{}
paddy@66 114 data.Set("grant", "approved")
paddy@66 115 body := bytes.NewBufferString(data.Encode())
paddy@66 116 req.Body = ioutil.NopCloser(body)
paddy@66 117 GetGrantHandler(w, req, testContext)
paddy@66 118 if w.Code != http.StatusFound {
paddy@66 119 t.Errorf("Expected status code to be %d, got %d for %s", http.StatusFound, w.Code, req.URL.String())
paddy@66 120 }
paddy@66 121 redirectedTo := w.Header().Get("Location")
paddy@66 122 red, err := url.Parse(redirectedTo)
paddy@66 123 if err != nil {
paddy@66 124 t.Fatalf(`Being redirected to a non-URL "%s" threw error "%s" for "%s"\n`, redirectedTo, err, req.URL.String())
paddy@66 125 }
paddy@66 126 t.Log("Redirected to", redirectedTo)
paddy@66 127 if red.Query().Get("code") == "" {
paddy@66 128 t.Fatalf(`Expected code param in redirect URL to be set, but it wasn't for %s`, req.URL.String())
paddy@66 129 }
paddy@67 130 if _, err := testContext.GetGrant(red.Query().Get("code")); err != nil {
paddy@67 131 t.Fatalf(`Unexpected error "%s: retrieving the grant "%s" supplied in the redirect URL for %s`, err, red.Query().Get("code"), req.URL.String())
paddy@66 132 }
paddy@66 133 err = testContext.DeleteGrant(red.Query().Get("code"))
paddy@66 134 if err != nil {
paddy@82 135 t.Logf(`Unexpected error "%s" deleting grant "%s" for %s`, err, red.Query().Get("code"), req.URL.String())
paddy@66 136 }
paddy@66 137 stripParam("code", red)
paddy@66 138 if red.Query().Get("state") != params.Get("state") {
paddy@66 139 t.Errorf(`Expected state param in redirect URL to be "%s", got "%s" for %s`, params.Get("state"), red.Query().Get("state"), req.URL.String())
paddy@66 140 }
paddy@66 141 stripParam("state", red)
paddy@66 142 if red.String() != endpoint.URI.String() {
paddy@66 143 t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
paddy@66 144 }
paddy@52 145 }
paddy@52 146 }
paddy@56 147
paddy@62 148 func TestGetGrantCodeInvalidClient(t *testing.T) {
paddy@62 149 t.Parallel()
paddy@62 150 store := NewMemstore()
paddy@62 151 testContext := Context{
paddy@62 152 template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
paddy@62 153 clients: store,
paddy@62 154 grants: store,
paddy@62 155 profiles: store,
paddy@62 156 tokens: store,
paddy@77 157 sessions: store,
paddy@62 158 }
paddy@62 159 client := Client{
paddy@62 160 ID: uuid.NewID(),
paddy@62 161 Secret: "super secret!",
paddy@62 162 OwnerID: uuid.NewID(),
paddy@62 163 Name: "My test client",
paddy@62 164 Type: "public",
paddy@62 165 }
paddy@62 166 err := testContext.SaveClient(client)
paddy@62 167 if err != nil {
paddy@62 168 t.Fatal("Can't store client:", err)
paddy@62 169 }
paddy@77 170 session := Session{
paddy@77 171 ID: "testsession",
paddy@77 172 Active: true,
paddy@77 173 }
paddy@77 174 err = testContext.CreateSession(session)
paddy@77 175 if err != nil {
paddy@77 176 t.Fatal("Can't store session:", err)
paddy@77 177 }
paddy@62 178 req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
paddy@62 179 if err != nil {
paddy@62 180 t.Fatal("Can't build request:", err)
paddy@62 181 }
paddy@62 182 w := httptest.NewRecorder()
paddy@62 183 params := url.Values{}
paddy@62 184 params.Set("response_type", "code")
paddy@62 185 params.Set("redirect_uri", "https://test.secondbit.org/")
paddy@62 186 req.URL.RawQuery = params.Encode()
paddy@77 187 cookie := &http.Cookie{
paddy@77 188 Name: authCookieName,
paddy@77 189 Value: session.ID,
paddy@77 190 }
paddy@77 191 req.AddCookie(cookie)
paddy@62 192 GetGrantHandler(w, req, testContext)
paddy@62 193 if w.Code != http.StatusBadRequest {
paddy@62 194 t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
paddy@62 195 }
paddy@62 196 if w.Body.String() != "Client ID must be specified in the request." {
paddy@62 197 t.Errorf(`Expected output to be "%s", got "%s" instead.`, "Client ID must be specified in the request.", w.Body.String())
paddy@62 198 }
paddy@62 199 w = httptest.NewRecorder()
paddy@62 200 params.Set("client_id", "Not an ID")
paddy@62 201 req.URL.RawQuery = params.Encode()
paddy@62 202 GetGrantHandler(w, req, testContext)
paddy@62 203 if w.Code != http.StatusBadRequest {
paddy@62 204 t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
paddy@62 205 }
paddy@62 206 if w.Body.String() != "client_id is not a valid Client ID." {
paddy@62 207 t.Errorf(`Expected output to be "%s", got "%s" instead.`, "client_id is not a valid Client ID.", w.Body.String())
paddy@62 208 }
paddy@62 209 w = httptest.NewRecorder()
paddy@62 210 params.Set("client_id", uuid.NewID().String())
paddy@62 211 req.URL.RawQuery = params.Encode()
paddy@62 212 GetGrantHandler(w, req, testContext)
paddy@62 213 if w.Code != http.StatusBadRequest {
paddy@62 214 t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
paddy@62 215 }
paddy@62 216 if w.Body.String() != "The specified Client couldn&rsquo;t be found." {
paddy@62 217 t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The specified Client couldn&rsquo;t be found.", w.Body.String())
paddy@62 218 }
paddy@62 219 }
paddy@62 220
paddy@56 221 func TestGetGrantCodeInvalidURI(t *testing.T) {
paddy@56 222 t.Parallel()
paddy@56 223 store := NewMemstore()
paddy@56 224 testContext := Context{
paddy@56 225 template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
paddy@56 226 clients: store,
paddy@56 227 grants: store,
paddy@56 228 profiles: store,
paddy@56 229 tokens: store,
paddy@77 230 sessions: store,
paddy@56 231 }
paddy@56 232 client := Client{
paddy@56 233 ID: uuid.NewID(),
paddy@56 234 Secret: "super secret!",
paddy@56 235 OwnerID: uuid.NewID(),
paddy@56 236 Name: "My test client",
paddy@56 237 Type: "public",
paddy@56 238 }
paddy@56 239 uri, err := url.Parse("https://test.secondbit.org/redirect")
paddy@56 240 if err != nil {
paddy@56 241 t.Fatal("Can't parse URL:", err)
paddy@56 242 }
paddy@56 243 err = testContext.SaveClient(client)
paddy@56 244 if err != nil {
paddy@56 245 t.Fatal("Can't store client:", err)
paddy@56 246 }
paddy@77 247 session := Session{
paddy@77 248 ID: "testsession",
paddy@77 249 Active: true,
paddy@77 250 }
paddy@77 251 err = testContext.CreateSession(session)
paddy@77 252 if err != nil {
paddy@77 253 t.Fatal("Can't store session:", err)
paddy@77 254 }
paddy@56 255 req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
paddy@56 256 if err != nil {
paddy@56 257 t.Fatal("Can't build request:", err)
paddy@56 258 }
paddy@77 259 cookie := &http.Cookie{
paddy@77 260 Name: authCookieName,
paddy@77 261 Value: session.ID,
paddy@77 262 }
paddy@77 263 req.AddCookie(cookie)
paddy@56 264 w := httptest.NewRecorder()
paddy@56 265 params := url.Values{}
paddy@56 266 params.Set("response_type", "code")
paddy@56 267 params.Set("client_id", client.ID.String())
paddy@64 268 req.URL.RawQuery = params.Encode()
paddy@64 269 GetGrantHandler(w, req, testContext)
paddy@64 270 if w.Code != http.StatusBadRequest {
paddy@64 271 t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
paddy@64 272 }
paddy@64 273 if w.Body.String() != "The redirect_uri specified is not valid." {
paddy@64 274 t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
paddy@64 275 }
paddy@64 276 endpoint := Endpoint{
paddy@64 277 ID: uuid.NewID(),
paddy@64 278 ClientID: client.ID,
paddy@64 279 URI: *uri,
paddy@64 280 Added: time.Now(),
paddy@64 281 }
paddy@64 282 err = testContext.AddEndpoint(client.ID, endpoint)
paddy@64 283 if err != nil {
paddy@64 284 t.Fatal("Can't store endpoint:", err)
paddy@64 285 }
paddy@64 286 w = httptest.NewRecorder()
paddy@56 287 params.Set("redirect_uri", "https://test.secondbit.org/wrong")
paddy@56 288 req.URL.RawQuery = params.Encode()
paddy@56 289 GetGrantHandler(w, req, testContext)
paddy@56 290 if w.Code != http.StatusBadRequest {
paddy@56 291 t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
paddy@56 292 }
paddy@56 293 if w.Body.String() != "The redirect_uri specified is not valid." {
paddy@56 294 t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
paddy@56 295 }
paddy@64 296 endpoint2 := Endpoint{
paddy@64 297 ID: uuid.NewID(),
paddy@64 298 ClientID: client.ID,
paddy@64 299 URI: *uri,
paddy@64 300 Added: time.Now(),
paddy@64 301 }
paddy@64 302 err = testContext.AddEndpoint(client.ID, endpoint2)
paddy@60 303 if err != nil {
paddy@64 304 t.Fatal("Can't store endpoint:", err)
paddy@60 305 }
paddy@60 306 w = httptest.NewRecorder()
paddy@64 307 params.Set("redirect_uri", "")
paddy@64 308 req.URL.RawQuery = params.Encode()
paddy@64 309 GetGrantHandler(w, req, testContext)
paddy@64 310 if w.Code != http.StatusBadRequest {
paddy@64 311 t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
paddy@64 312 }
paddy@64 313 if w.Body.String() != "The redirect_uri specified is not valid." {
paddy@64 314 t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
paddy@64 315 }
paddy@64 316 w = httptest.NewRecorder()
paddy@64 317 params.Set("redirect_uri", "://not a URL")
paddy@60 318 req.URL.RawQuery = params.Encode()
paddy@60 319 GetGrantHandler(w, req, testContext)
paddy@60 320 if w.Code != http.StatusBadRequest {
paddy@60 321 t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
paddy@60 322 }
paddy@60 323 if w.Body.String() != "The redirect_uri specified is not valid." {
paddy@60 324 t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
paddy@60 325 }
paddy@56 326 }
paddy@65 327
paddy@65 328 func TestGetGrantCodeInvalidResponseType(t *testing.T) {
paddy@65 329 t.Parallel()
paddy@65 330 store := NewMemstore()
paddy@65 331 testContext := Context{
paddy@65 332 template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
paddy@65 333 clients: store,
paddy@65 334 grants: store,
paddy@65 335 profiles: store,
paddy@65 336 tokens: store,
paddy@77 337 sessions: store,
paddy@65 338 }
paddy@65 339 client := Client{
paddy@65 340 ID: uuid.NewID(),
paddy@65 341 Secret: "super secret!",
paddy@65 342 OwnerID: uuid.NewID(),
paddy@65 343 Name: "My test client",
paddy@65 344 Logo: "https://secondbit.org/logo.png",
paddy@65 345 Website: "https://secondbit.org",
paddy@65 346 Type: "public",
paddy@65 347 }
paddy@65 348 uri, err := url.Parse("https://test.secondbit.org/redirect")
paddy@65 349 if err != nil {
paddy@65 350 t.Fatal("Can't parse URL:", err)
paddy@65 351 }
paddy@65 352 endpoint := Endpoint{
paddy@65 353 ID: uuid.NewID(),
paddy@65 354 ClientID: client.ID,
paddy@65 355 URI: *uri,
paddy@65 356 Added: time.Now(),
paddy@65 357 }
paddy@65 358 err = testContext.SaveClient(client)
paddy@65 359 if err != nil {
paddy@65 360 t.Fatal("Can't store client:", err)
paddy@65 361 }
paddy@65 362 err = testContext.AddEndpoint(client.ID, endpoint)
paddy@65 363 if err != nil {
paddy@65 364 t.Fatal("Can't store endpoint:", err)
paddy@65 365 }
paddy@77 366 session := Session{
paddy@77 367 ID: "testsession",
paddy@77 368 Active: true,
paddy@77 369 }
paddy@77 370 err = testContext.CreateSession(session)
paddy@77 371 if err != nil {
paddy@77 372 t.Fatal("Can't store session:", err)
paddy@77 373 }
paddy@65 374 req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
paddy@65 375 if err != nil {
paddy@65 376 t.Fatal("Can't build request:", err)
paddy@65 377 }
paddy@77 378 cookie := &http.Cookie{
paddy@77 379 Name: authCookieName,
paddy@77 380 Value: session.ID,
paddy@77 381 }
paddy@77 382 req.AddCookie(cookie)
paddy@65 383 params := url.Values{}
paddy@65 384 params.Set("response_type", "totally not code")
paddy@65 385 params.Set("client_id", client.ID.String())
paddy@65 386 params.Set("redirect_uri", endpoint.URI.String())
paddy@65 387 params.Set("scope", "testscope")
paddy@65 388 params.Set("state", "my super secure state string")
paddy@65 389 req.URL.RawQuery = params.Encode()
paddy@65 390 w := httptest.NewRecorder()
paddy@65 391 GetGrantHandler(w, req, testContext)
paddy@65 392 if w.Code != http.StatusFound {
paddy@65 393 t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
paddy@65 394 }
paddy@65 395 redirectedTo := w.Header().Get("Location")
paddy@65 396 red, err := url.Parse(redirectedTo)
paddy@65 397 if err != nil {
paddy@65 398 t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
paddy@65 399 }
paddy@65 400 if red.Query().Get("error") != "invalid_request" {
paddy@65 401 t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "invalid_request", red.Query().Get("error"))
paddy@65 402 }
paddy@65 403 stripParam("error", red)
paddy@65 404 if red.Query().Get("state") != params.Get("state") {
paddy@65 405 t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
paddy@65 406 }
paddy@65 407 stripParam("state", red)
paddy@65 408 if red.String() != endpoint.URI.String() {
paddy@65 409 t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
paddy@65 410 }
paddy@65 411 stripParam("response_type", req.URL)
paddy@65 412 w = httptest.NewRecorder()
paddy@65 413 GetGrantHandler(w, req, testContext)
paddy@65 414 if w.Code != http.StatusFound {
paddy@65 415 t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
paddy@65 416 }
paddy@65 417 redirectedTo = w.Header().Get("Location")
paddy@65 418 red, err = url.Parse(redirectedTo)
paddy@65 419 if err != nil {
paddy@65 420 t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
paddy@65 421 }
paddy@65 422 if red.Query().Get("error") != "invalid_request" {
paddy@65 423 t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "invalid_request", red.Query().Get("error"))
paddy@65 424 }
paddy@65 425 stripParam("error", red)
paddy@65 426 if red.Query().Get("state") != params.Get("state") {
paddy@65 427 t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
paddy@65 428 }
paddy@65 429 stripParam("state", red)
paddy@65 430 if red.String() != endpoint.URI.String() {
paddy@65 431 t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
paddy@65 432 }
paddy@65 433 }
paddy@66 434
paddy@66 435 func TestGetGrantCodeDenied(t *testing.T) {
paddy@66 436 t.Parallel()
paddy@66 437 store := NewMemstore()
paddy@66 438 testContext := Context{
paddy@66 439 template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
paddy@66 440 clients: store,
paddy@66 441 grants: store,
paddy@66 442 profiles: store,
paddy@66 443 tokens: store,
paddy@77 444 sessions: store,
paddy@66 445 }
paddy@66 446 client := Client{
paddy@66 447 ID: uuid.NewID(),
paddy@66 448 Secret: "super secret!",
paddy@66 449 OwnerID: uuid.NewID(),
paddy@66 450 Name: "My test client",
paddy@66 451 Logo: "https://secondbit.org/logo.png",
paddy@66 452 Website: "https://secondbit.org",
paddy@66 453 Type: "public",
paddy@66 454 }
paddy@66 455 uri, err := url.Parse("https://test.secondbit.org/redirect")
paddy@66 456 if err != nil {
paddy@66 457 t.Fatal("Can't parse URL:", err)
paddy@66 458 }
paddy@66 459 endpoint := Endpoint{
paddy@66 460 ID: uuid.NewID(),
paddy@66 461 ClientID: client.ID,
paddy@66 462 URI: *uri,
paddy@66 463 Added: time.Now(),
paddy@66 464 }
paddy@66 465 err = testContext.SaveClient(client)
paddy@66 466 if err != nil {
paddy@66 467 t.Fatal("Can't store client:", err)
paddy@66 468 }
paddy@66 469 err = testContext.AddEndpoint(client.ID, endpoint)
paddy@66 470 if err != nil {
paddy@66 471 t.Fatal("Can't store endpoint:", err)
paddy@66 472 }
paddy@77 473 session := Session{
paddy@77 474 ID: "testsession",
paddy@77 475 Active: true,
paddy@77 476 }
paddy@77 477 err = testContext.CreateSession(session)
paddy@77 478 if err != nil {
paddy@77 479 t.Fatal("Can't store session:", err)
paddy@77 480 }
paddy@66 481 req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
paddy@66 482 if err != nil {
paddy@66 483 t.Fatal("Can't build request:", err)
paddy@66 484 }
paddy@77 485 cookie := &http.Cookie{
paddy@77 486 Name: authCookieName,
paddy@77 487 Value: session.ID,
paddy@77 488 }
paddy@77 489 req.AddCookie(cookie)
paddy@66 490 params := url.Values{}
paddy@66 491 params.Set("response_type", "code")
paddy@66 492 params.Set("client_id", client.ID.String())
paddy@66 493 params.Set("redirect_uri", endpoint.URI.String())
paddy@66 494 params.Set("scope", "testscope")
paddy@66 495 params.Set("state", "my super secure state string")
paddy@66 496 data := url.Values{}
paddy@66 497 data.Set("grant", "denied")
paddy@66 498 req.URL.RawQuery = params.Encode()
paddy@66 499 req.Body = ioutil.NopCloser(bytes.NewBufferString(data.Encode()))
paddy@66 500 req.Method = "POST"
paddy@66 501 w := httptest.NewRecorder()
paddy@66 502 GetGrantHandler(w, req, testContext)
paddy@66 503 if w.Code != http.StatusFound {
paddy@66 504 t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
paddy@66 505 }
paddy@66 506 redirectedTo := w.Header().Get("Location")
paddy@66 507 red, err := url.Parse(redirectedTo)
paddy@66 508 if err != nil {
paddy@66 509 t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
paddy@66 510 }
paddy@66 511 if red.Query().Get("error") != "access_denied" {
paddy@66 512 t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "access_denied", red.Query().Get("error"))
paddy@66 513 }
paddy@66 514 stripParam("error", red)
paddy@66 515 if red.Query().Get("state") != params.Get("state") {
paddy@66 516 t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
paddy@66 517 }
paddy@66 518 stripParam("state", red)
paddy@66 519 if red.String() != endpoint.URI.String() {
paddy@66 520 t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
paddy@66 521 }
paddy@66 522 }
paddy@77 523
paddy@80 524 func TestGetGrantCodeLoginRedirect(t *testing.T) {
paddy@80 525 t.Parallel()
paddy@80 526 req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
paddy@80 527 if err != nil {
paddy@80 528 t.Fatal("Can't build request:", err)
paddy@80 529 }
paddy@80 530 w := httptest.NewRecorder()
paddy@80 531 GetGrantHandler(w, req, Context{template: template.Must(template.New(getGrantTemplateName).Parse("{{ .internal_error }}"))})
paddy@80 532 if w.Code != http.StatusInternalServerError {
paddy@80 533 t.Errorf("Expected status code to be %d, got %d", http.StatusInternalServerError, w.Code)
paddy@80 534 }
paddy@80 535 expectation := "Missing login URL."
paddy@80 536 if w.Body.String() != expectation {
paddy@80 537 t.Errorf(`Expected body to be "%s", got "%s"`, expectation, w.Body.String())
paddy@80 538 }
paddy@80 539 uri, err := url.Parse("https://client.secondbit.org/")
paddy@80 540 if err != nil {
paddy@82 541 t.Error("Unexpected error", err)
paddy@80 542 }
paddy@80 543 testContext := Context{
paddy@80 544 loginURI: uri,
paddy@80 545 }
paddy@80 546 w = httptest.NewRecorder()
paddy@80 547 GetGrantHandler(w, req, testContext)
paddy@80 548 if w.Code != http.StatusFound {
paddy@80 549 t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
paddy@80 550 }
paddy@80 551 redirectedTo := w.Header().Get("Location")
paddy@80 552 expectation = "https://client.secondbit.org/?from=https%3A%2F%2Ftest.auth.secondbit.org%2Foauth2%2Fgrant"
paddy@80 553 if redirectedTo != expectation {
paddy@80 554 t.Errorf("Expected to be redirected to '%s', was redirected to '%s'", expectation, redirectedTo)
paddy@80 555 }
paddy@80 556 }
paddy@80 557
paddy@78 558 func TestCheckCookie(t *testing.T) {
paddy@78 559 t.Parallel()
paddy@78 560 req, err := http.NewRequest("GET", "https://auth.secondbit.org", nil)
paddy@78 561 if err != nil {
paddy@78 562 t.Error("Unexpected error creating base request:", err)
paddy@78 563 }
paddy@78 564 store := NewMemstore()
paddy@78 565 testContext := Context{
paddy@78 566 sessions: store,
paddy@78 567 }
paddy@78 568 session, err := checkCookie(req, testContext)
paddy@78 569 if err != ErrNoSession {
paddy@78 570 t.Errorf("Expected ErrNoSession, got %s", err)
paddy@78 571 }
paddy@78 572 session = Session{
paddy@78 573 ID: "testsession",
paddy@78 574 Active: true,
paddy@78 575 }
paddy@78 576 err = testContext.CreateSession(session)
paddy@78 577 if err != nil {
paddy@78 578 t.Error("Unexpected error persisting session:", err)
paddy@78 579 }
paddy@78 580 invalidSession := Session{
paddy@78 581 ID: "testsession2",
paddy@78 582 Active: false,
paddy@78 583 }
paddy@78 584 err = testContext.CreateSession(invalidSession)
paddy@78 585 if err != nil {
paddy@78 586 t.Error("Unexpected error persisting session:", err)
paddy@78 587 }
paddy@78 588 result, err := checkCookie(req, testContext)
paddy@78 589 if err != ErrNoSession {
paddy@78 590 t.Errorf("Expected ErrNoSession, got %s", err)
paddy@78 591 }
paddy@78 592 req.AddCookie(&http.Cookie{
paddy@78 593 Name: "wrongcookie",
paddy@78 594 Value: "wrong value",
paddy@78 595 })
paddy@78 596 result, err = checkCookie(req, testContext)
paddy@78 597 if err != ErrNoSession {
paddy@78 598 t.Error("Expected ErrNoSession, got", err)
paddy@78 599 }
paddy@78 600 req, err = http.NewRequest("GET", "https://auth.secondbit.org", nil)
paddy@78 601 if err != nil {
paddy@78 602 t.Error("Unexpected error creating base request:", err)
paddy@78 603 }
paddy@78 604 req.AddCookie(&http.Cookie{
paddy@78 605 Name: "Stillwrongcookie",
paddy@78 606 Value: session.ID,
paddy@78 607 })
paddy@78 608 result, err = checkCookie(req, testContext)
paddy@78 609 if err != ErrNoSession {
paddy@78 610 t.Error("Expected ErrNoSession, got", err)
paddy@78 611 }
paddy@78 612 req, err = http.NewRequest("GET", "https://auth.secondbit.org", nil)
paddy@78 613 if err != nil {
paddy@78 614 t.Error("Unexpected error creating base request:", err)
paddy@78 615 }
paddy@78 616 req.AddCookie(&http.Cookie{
paddy@78 617 Name: authCookieName,
paddy@78 618 Value: "wrong value",
paddy@78 619 })
paddy@78 620 result, err = checkCookie(req, testContext)
paddy@78 621 if err != ErrInvalidSession {
paddy@78 622 t.Error("Expected ErrInvalidSession, got", err)
paddy@78 623 }
paddy@78 624 req, err = http.NewRequest("GET", "https://auth.secondbit.org", nil)
paddy@78 625 if err != nil {
paddy@78 626 t.Error("Unexpected error creating base request:", err)
paddy@78 627 }
paddy@78 628 req.AddCookie(&http.Cookie{
paddy@78 629 Name: authCookieName,
paddy@78 630 Value: invalidSession.ID,
paddy@78 631 })
paddy@78 632 result, err = checkCookie(req, testContext)
paddy@78 633 if err != ErrInvalidSession {
paddy@78 634 t.Error("Expected ErrInvalidSession, got", err)
paddy@78 635 }
paddy@78 636 req, err = http.NewRequest("GET", "https://auth.secondbit.org", nil)
paddy@78 637 if err != nil {
paddy@78 638 t.Error("Unexpected error creating base request:", err)
paddy@78 639 }
paddy@78 640 req.AddCookie(&http.Cookie{
paddy@78 641 Name: authCookieName,
paddy@78 642 Value: session.ID,
paddy@78 643 })
paddy@78 644 result, err = checkCookie(req, testContext)
paddy@78 645 if err != nil {
paddy@78 646 t.Error("Unexpected error:", err)
paddy@78 647 }
paddy@78 648 success, field, expectation, outcome := compareSessions(session, result)
paddy@78 649 if !success {
paddy@78 650 t.Errorf(`Expected field %s to be %v, but got %v`, field, expectation, outcome)
paddy@78 651 }
paddy@78 652 }
paddy@78 653
paddy@78 654 func TestBuildLoginRedirect(t *testing.T) {
paddy@78 655 t.Parallel()
paddy@78 656 req, err := http.NewRequest("GET", "https://client.secondbit.org/my/awesome/path?has=query&params=to&screw=this&all=up", nil)
paddy@78 657 if err != nil {
paddy@78 658 t.Error("Unexpected error creating base request:", err)
paddy@78 659 }
paddy@78 660 result := buildLoginRedirect(req, Context{})
paddy@78 661 if result != "" {
paddy@78 662 t.Error("Expected empty string as the result, got", result)
paddy@78 663 }
paddy@78 664 uri, err := url.Parse("https://auth.secondbit.org/login?query=string&other=param")
paddy@78 665 if err != nil {
paddy@78 666 t.Error("Unexpected error parsing URL:", err)
paddy@78 667 }
paddy@78 668 c := Context{loginURI: uri}
paddy@78 669 result = buildLoginRedirect(req, c)
paddy@78 670 expectation := "https://auth.secondbit.org/login?from=https%3A%2F%2Fclient.secondbit.org%2Fmy%2Fawesome%2Fpath%3Fhas%3Dquery%26params%3Dto%26screw%3Dthis%26all%3Dup&other=param&query=string"
paddy@78 671 if result != expectation {
paddy@78 672 t.Errorf(`Expected result string to be "%s", was "%s"`, expectation, result)
paddy@78 673 }
paddy@78 674 }
paddy@79 675
paddy@79 676 func TestAuthenticateHelper(t *testing.T) {
paddy@79 677 t.Parallel()
paddy@79 678 store := NewMemstore()
paddy@79 679 context := Context{
paddy@79 680 profiles: store,
paddy@79 681 }
paddy@79 682 profile := Profile{
paddy@79 683 ID: uuid.NewID(),
paddy@79 684 Name: "Test User",
paddy@79 685 Passphrase: "55d87acb9adff90a0d8e4c9b77f239c2d6e3a1945dbd09b0270467411198db25",
paddy@79 686 Iterations: 4096,
paddy@79 687 Salt: "this is a super secure random salt",
paddy@79 688 PassphraseScheme: 1,
paddy@79 689 Compromised: false,
paddy@79 690 LockedUntil: time.Time{},
paddy@79 691 PassphraseReset: "",
paddy@79 692 PassphraseResetCreated: time.Time{},
paddy@79 693 Created: time.Now(),
paddy@79 694 LastSeen: time.Time{},
paddy@79 695 }
paddy@79 696 login := Login{
paddy@79 697 Type: "email",
paddy@79 698 Value: "test@example.com",
paddy@79 699 ProfileID: profile.ID,
paddy@79 700 Created: time.Now(),
paddy@79 701 LastUsed: time.Time{},
paddy@79 702 }
paddy@79 703 err := context.SaveProfile(profile)
paddy@79 704 if err != nil {
paddy@79 705 t.Error("Error saving profile:", err)
paddy@79 706 }
paddy@79 707 err = context.AddLogin(login)
paddy@79 708 if err != nil {
paddy@79 709 t.Error("Error adding login:", err)
paddy@79 710 }
paddy@79 711 response, err := authenticate("test@example.com", "a really secure password", context)
paddy@79 712 if err != nil {
paddy@79 713 t.Error("Unexpected error:", err)
paddy@79 714 }
paddy@79 715 success, field, expectation, result := compareProfiles(profile, response)
paddy@79 716 if !success {
paddy@79 717 t.Errorf(`Expected field %s to be "%v", got "%v"`, field, expectation, result)
paddy@79 718 }
paddy@79 719 response, err = authenticate("test2@example.com", "a really secure password", context)
paddy@79 720 if err != ErrIncorrectAuth {
paddy@79 721 t.Error("Expected ErrIncorrectAuth, got", err)
paddy@79 722 }
paddy@79 723 response, err = authenticate("test@example.com", "not the right password", context)
paddy@79 724 if err != ErrIncorrectAuth {
paddy@79 725 t.Error("Expected ErrIncorrectAuth, got", err)
paddy@79 726 }
paddy@79 727 scheme := 1000
paddy@79 728 phrase := "doesn't really matter, the scheme doesn't exist"
paddy@79 729 change := ProfileChange{
paddy@79 730 PassphraseScheme: &scheme,
paddy@79 731 Passphrase: &phrase,
paddy@79 732 }
paddy@79 733 err = context.UpdateProfile(profile.ID, change)
paddy@79 734 if err != nil {
paddy@79 735 t.Error("Unexpected error:", err)
paddy@79 736 }
paddy@79 737 response, err = authenticate("test@example.com", "not the right password", context)
paddy@79 738 if err != ErrInvalidPassphraseScheme {
paddy@79 739 t.Error("Expected ErrIncorrectAuth, got", err)
paddy@79 740 }
paddy@79 741 }
paddy@81 742
paddy@81 743 func TestGetTokenHandler(t *testing.T) {
paddy@81 744 t.Parallel()
paddy@81 745 store := NewMemstore()
paddy@81 746 context := Context{
paddy@81 747 clients: store,
paddy@81 748 grants: store,
paddy@81 749 tokens: store,
paddy@81 750 }
paddy@81 751 client := Client{
paddy@81 752 ID: uuid.NewID(),
paddy@81 753 Secret: "sometimes I feel like I don't know what I'm doing",
paddy@81 754 OwnerID: uuid.NewID(),
paddy@81 755 Name: "A Super Awesome Client!",
paddy@81 756 Logo: "https://logos.secondbit.org/client.png",
paddy@81 757 Website: "https://client.secondbit.org/",
paddy@81 758 Type: "confidential",
paddy@81 759 }
paddy@81 760 grant := Grant{
paddy@81 761 Code: "testcode",
paddy@81 762 Created: time.Now(),
paddy@81 763 ExpiresIn: 600,
paddy@81 764 ClientID: client.ID,
paddy@81 765 Scope: "testscope",
paddy@81 766 RedirectURI: "https://client.secondbit.org/",
paddy@81 767 State: "teststate",
paddy@81 768 ProfileID: uuid.NewID(),
paddy@81 769 }
paddy@81 770 err := context.SaveGrant(grant)
paddy@81 771 if err != nil {
paddy@81 772 t.Error("Error saving grant:", err)
paddy@81 773 }
paddy@81 774 err = context.SaveClient(client)
paddy@81 775 if err != nil {
paddy@81 776 t.Error("Error saving client:", err)
paddy@81 777 }
paddy@81 778 data := url.Values{}
paddy@81 779 data.Set("grant_type", "authorization_code")
paddy@81 780 data.Set("code", grant.Code)
paddy@81 781 data.Set("redirect_uri", grant.RedirectURI)
paddy@81 782 body := bytes.NewBufferString(data.Encode())
paddy@81 783 req, err := http.NewRequest("POST", "https://auth.secondbit.org/", ioutil.NopCloser(body))
paddy@81 784 if err != nil {
paddy@81 785 t.Error("Error constructing request:", err)
paddy@81 786 }
paddy@81 787 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
paddy@81 788 req.SetBasicAuth(client.ID.String(), client.Secret)
paddy@81 789 w := httptest.NewRecorder()
paddy@81 790 GetTokenHandler(w, req, context)
paddy@81 791 resp := tokenResponse{}
paddy@81 792 err = json.Unmarshal(w.Body.Bytes(), &resp)
paddy@81 793 if err != nil {
paddy@81 794 t.Error("Error unmarshalling response:", err)
paddy@81 795 }
paddy@81 796 if resp.AccessToken == "" {
paddy@81 797 t.Error("Got blank access token back")
paddy@81 798 }
paddy@81 799 if resp.RefreshToken == "" {
paddy@81 800 t.Error("Got blank refresh token back")
paddy@81 801 }
paddy@81 802 if resp.TokenType == "" {
paddy@81 803 t.Error("Got blank token type back")
paddy@81 804 }
paddy@81 805 if resp.ExpiresIn == 0 {
paddy@81 806 t.Error("Got blank expires in back")
paddy@81 807 }
paddy@81 808 tokens, err := context.GetTokensByProfileID(grant.ProfileID, 1, 0)
paddy@81 809 if err != nil {
paddy@81 810 t.Error("Error retrieving token:", err)
paddy@81 811 }
paddy@81 812 if len(tokens) != 1 {
paddy@81 813 t.Errorf("Expected %d tokens, got %d", 1, len(tokens))
paddy@81 814 }
paddy@81 815 if tokens[0].AccessToken != resp.AccessToken {
paddy@81 816 t.Errorf(`Expected access token to be "%s", got "%s"`, tokens[0].AccessToken, resp.AccessToken)
paddy@81 817 }
paddy@81 818 if tokens[0].RefreshToken != resp.RefreshToken {
paddy@81 819 t.Errorf(`Expected refresh token to be "%s", got "%s"`, tokens[0].RefreshToken, resp.RefreshToken)
paddy@81 820 }
paddy@81 821 if tokens[0].ExpiresIn != resp.ExpiresIn {
paddy@81 822 t.Errorf(`Expected expires in to be %d, got %d`, tokens[0].ExpiresIn, resp.ExpiresIn)
paddy@81 823 }
paddy@81 824 if tokens[0].TokenType != resp.TokenType {
paddy@81 825 t.Errorf(`Expected token type to be %s, got %s`, tokens[0].TokenType, resp.TokenType)
paddy@81 826 }
paddy@81 827 }