github.com/blend/go-sdk@v1.20220411.3/webutil/decode_basic_auth_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  import (
    11  	"net/http"
    12  	"testing"
    13  
    14  	"github.com/blend/go-sdk/assert"
    15  )
    16  
    17  func TestDecodeBasicAuth(t *testing.T) {
    18  	assert := assert.New(t)
    19  
    20  	req, err := http.NewRequest("GET", "http://example.invalid", nil)
    21  	assert.Nil(err)
    22  
    23  	// No authorization header.
    24  	_, _, err = DecodeBasicAuth(req)
    25  	assert.True(ErrIsUnauthorized(err))
    26  
    27  	// Authorization header not in form "Basic ..."
    28  	req.Header.Set(HeaderAuthorization, "not-basic")
    29  	_, _, err = DecodeBasicAuth(req)
    30  	assert.True(ErrIsUnauthorized(err))
    31  	req.Header.Set(HeaderAuthorization, "NotBasic bHVsei1zZWNyZXQ=")
    32  	_, _, err = DecodeBasicAuth(req)
    33  	assert.True(ErrIsUnauthorized(err))
    34  
    35  	// With authorization header; invalid base64
    36  	req.Header.Set(HeaderAuthorization, "Basic ???")
    37  	_, _, err = DecodeBasicAuth(req)
    38  	assert.True(ErrIsUnauthorized(err))
    39  
    40  	// With authorization header; base64 encoded content not in form `un:pw`
    41  	req.Header.Set(HeaderAuthorization, "Basic bHVsei1zZWNyZXQ=")
    42  	_, _, err = DecodeBasicAuth(req)
    43  	assert.True(ErrIsUnauthorized(err))
    44  
    45  	// With authorization header; valid base64 header
    46  	req.Header.Set(HeaderAuthorization, "Basic am9leUBtYWlsLmludmFsaWQ6cHdzMzNrciF0")
    47  	username, password, err := DecodeBasicAuth(req)
    48  	assert.Nil(err)
    49  	assert.Equal(username, "joey@mail.invalid")
    50  	assert.Equal(password, "pws33kr!t")
    51  }