github.com/ashishbhate/mattermost-server@v5.11.1+incompatible/utils/api_test.go (about)

     1  // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package utils
     5  
     6  import (
     7  	"crypto/ecdsa"
     8  	"crypto/elliptic"
     9  	"crypto/rand"
    10  	"crypto/sha256"
    11  	"encoding/asn1"
    12  	"encoding/base64"
    13  	"math/big"
    14  	"net/http"
    15  	"net/http/httptest"
    16  	"net/url"
    17  	"testing"
    18  
    19  	"github.com/stretchr/testify/assert"
    20  	"github.com/stretchr/testify/require"
    21  
    22  	"github.com/mattermost/mattermost-server/model"
    23  )
    24  
    25  func TestRenderWebError(t *testing.T) {
    26  	r := httptest.NewRequest("GET", "http://foo", nil)
    27  	w := httptest.NewRecorder()
    28  	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    29  	require.NoError(t, err)
    30  	RenderWebError(&model.Config{}, w, r, http.StatusTemporaryRedirect, url.Values{
    31  		"foo": []string{"bar"},
    32  	}, key)
    33  
    34  	resp := w.Result()
    35  	location, err := url.Parse(resp.Header.Get("Location"))
    36  	require.NoError(t, err)
    37  	require.NotEmpty(t, location.Query().Get("s"))
    38  
    39  	type ecdsaSignature struct {
    40  		R, S *big.Int
    41  	}
    42  	var rs ecdsaSignature
    43  	s, err := base64.URLEncoding.DecodeString(location.Query().Get("s"))
    44  	require.NoError(t, err)
    45  	_, err = asn1.Unmarshal(s, &rs)
    46  	require.NoError(t, err)
    47  
    48  	assert.Equal(t, "bar", location.Query().Get("foo"))
    49  	h := sha256.Sum256([]byte("/error?foo=bar"))
    50  	assert.True(t, ecdsa.Verify(&key.PublicKey, h[:], rs.R, rs.S))
    51  }