Path: blob/main/components/local-app/pkg/auth/auth_test.go
2500 views
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34//go:build linux && amd645// +build linux,amd6467package auth89import (10"context"11"crypto/sha256"12"encoding/hex"13"errors"14"net/http"15"testing"1617gitpod "github.com/gitpod-io/gitpod/gitpod-protocol"18"github.com/golang/mock/gomock"19"github.com/google/go-cmp/cmp"20)2122func TestValidateToken(t *testing.T) {23tkn := "foo"24hash := sha256.Sum256([]byte(tkn))25tokenHash := hex.EncodeToString(hash[:])2627unauthorizedErr := &gitpod.ErrBadHandshake{28Resp: &http.Response{29StatusCode: 401,30},31}3233forbiddenErr := errors.New("jsonrpc2: code 403 message: getGitpodTokenScopes")3435tests := []struct {36Desc string37Scopes []string38ScopesErr error39Expectation error40}{41{42Desc: "invalid: unauthorized",43ScopesErr: unauthorizedErr,44Expectation: &ErrInvalidGitpodToken{unauthorizedErr},45},46{47Desc: "invalid: forbidden",48ScopesErr: forbiddenErr,49Expectation: &ErrInvalidGitpodToken{forbiddenErr},50},51{52Desc: "invalid: missing scopes",53Scopes: []string{"function:getWorkspace"},54Expectation: &ErrInvalidGitpodToken{errors.New("function:getGitpodTokenScopes scope is missing in [function:getWorkspace]")},55},56{57Desc: "valid",58Scopes: authScopesLocalCompanion,59},60}61for _, test := range tests {62t.Run(test.Desc, func(t *testing.T) {63ctrl := gomock.NewController(t)64defer ctrl.Finish()6566gitpodAPI := gitpod.NewMockAPIInterface(ctrl)67gitpodAPI.EXPECT().GetGitpodTokenScopes(context.Background(), tokenHash).Times(1).Return(test.Scopes, test.ScopesErr)6869var expectation string70if test.Expectation != nil {71expectation = test.Expectation.Error()72}7374var actual string75err := ValidateToken(gitpodAPI, tkn)76if err != nil {77actual = err.Error()78}7980if diff := cmp.Diff(expectation, actual); diff != "" {81t.Errorf("unexpected output (-want +got):\n%s", diff)82}83})84}85}868788