Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/local-app/pkg/auth/auth_test.go
2500 views
1
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
//go:build linux && amd64
6
// +build linux,amd64
7
8
package auth
9
10
import (
11
"context"
12
"crypto/sha256"
13
"encoding/hex"
14
"errors"
15
"net/http"
16
"testing"
17
18
gitpod "github.com/gitpod-io/gitpod/gitpod-protocol"
19
"github.com/golang/mock/gomock"
20
"github.com/google/go-cmp/cmp"
21
)
22
23
func TestValidateToken(t *testing.T) {
24
tkn := "foo"
25
hash := sha256.Sum256([]byte(tkn))
26
tokenHash := hex.EncodeToString(hash[:])
27
28
unauthorizedErr := &gitpod.ErrBadHandshake{
29
Resp: &http.Response{
30
StatusCode: 401,
31
},
32
}
33
34
forbiddenErr := errors.New("jsonrpc2: code 403 message: getGitpodTokenScopes")
35
36
tests := []struct {
37
Desc string
38
Scopes []string
39
ScopesErr error
40
Expectation error
41
}{
42
{
43
Desc: "invalid: unauthorized",
44
ScopesErr: unauthorizedErr,
45
Expectation: &ErrInvalidGitpodToken{unauthorizedErr},
46
},
47
{
48
Desc: "invalid: forbidden",
49
ScopesErr: forbiddenErr,
50
Expectation: &ErrInvalidGitpodToken{forbiddenErr},
51
},
52
{
53
Desc: "invalid: missing scopes",
54
Scopes: []string{"function:getWorkspace"},
55
Expectation: &ErrInvalidGitpodToken{errors.New("function:getGitpodTokenScopes scope is missing in [function:getWorkspace]")},
56
},
57
{
58
Desc: "valid",
59
Scopes: authScopesLocalCompanion,
60
},
61
}
62
for _, test := range tests {
63
t.Run(test.Desc, func(t *testing.T) {
64
ctrl := gomock.NewController(t)
65
defer ctrl.Finish()
66
67
gitpodAPI := gitpod.NewMockAPIInterface(ctrl)
68
gitpodAPI.EXPECT().GetGitpodTokenScopes(context.Background(), tokenHash).Times(1).Return(test.Scopes, test.ScopesErr)
69
70
var expectation string
71
if test.Expectation != nil {
72
expectation = test.Expectation.Error()
73
}
74
75
var actual string
76
err := ValidateToken(gitpodAPI, tkn)
77
if err != nil {
78
actual = err.Error()
79
}
80
81
if diff := cmp.Diff(expectation, actual); diff != "" {
82
t.Errorf("unexpected output (-want +got):\n%s", diff)
83
}
84
})
85
}
86
}
87
88