summaryrefslogtreecommitdiff
path: root/internal/gitlabnet/personalaccesstoken/client_test.go
blob: 978866db10d63ebd4f5707c7b07eb942fe08dbea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package personalaccesstoken

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"testing"

	"github.com/stretchr/testify/require"
	gitnet "gitlab.com/gitlab-org/gitaly/v14/gitlabnet"
	"gitlab.com/gitlab-org/gitlab-shell/client/testserver"
	"gitlab.com/gitlab-org/gitlab-shell/internal/command/commandargs"
	"gitlab.com/gitlab-org/gitlab-shell/internal/config"
	"gitlab.com/gitlab-org/gitlab-shell/internal/gitlabnet/discover"
)

var (
	requests []testserver.TestRequestHandler
)

func initialize(t *testing.T) {
	requests = []testserver.TestRequestHandler{
		{
			Path: "/api/v4/internal/personal_access_token",
			Handler: func(w http.ResponseWriter, r *http.Request) {
				b, err := io.ReadAll(r.Body)
				defer r.Body.Close()

				require.NoError(t, err)

				var requestBody *RequestBody
				json.Unmarshal(b, &requestBody)

				switch requestBody.KeyId {
				case "0":
					body := map[string]interface{}{
						"success":    true,
						"token":      "aAY1G3YPeemECgUvxuXY",
						"scopes":     [2]string{"read_api", "read_repository"},
						"expires_at": "9001-11-17",
					}
					json.NewEncoder(w).Encode(body)
				case "1":
					body := map[string]interface{}{
						"success": false,
						"message": "missing user",
					}
					json.NewEncoder(w).Encode(body)
				case "2":
					w.WriteHeader(http.StatusForbidden)
					body := &gitnet.ErrorResponse{
						Message: "Not allowed!",
					}
					json.NewEncoder(w).Encode(body)
				case "3":
					w.Write([]byte("{ \"message\": \"broken json!\""))
				case "4":
					w.WriteHeader(http.StatusForbidden)
				}

				if requestBody.UserId == 1 {
					body := map[string]interface{}{
						"success":    true,
						"token":      "YXuxvUgCEmeePY3G1YAa",
						"scopes":     [1]string{"api"},
						"expires_at": nil,
					}
					json.NewEncoder(w).Encode(body)
				}
			},
		},
		{
			Path: "/api/v4/internal/discover",
			Handler: func(w http.ResponseWriter, r *http.Request) {
				body := &discover.Response{
					UserId:   1,
					Username: "jane-doe",
					Name:     "Jane Doe",
				}
				json.NewEncoder(w).Encode(body)
			},
		},
	}
}

func TestGetPersonalAccessTokenByKeyId(t *testing.T) {
	client := setup(t)

	args := &commandargs.Shell{GitlabKeyId: "0"}
	result, err := client.GetPersonalAccessToken(
		context.Background(), args, "newtoken", &[]string{"read_api", "read_repository"}, "",
	)
	require.NoError(t, err)
	response := &Response{
		true,
		"aAY1G3YPeemECgUvxuXY",
		[]string{"read_api", "read_repository"},
		"9001-11-17",
		"",
	}
	require.Equal(t, response, result)
}

func TestGetRecoveryCodesByUsername(t *testing.T) {
	client := setup(t)

	args := &commandargs.Shell{GitlabUsername: "jane-doe"}
	result, err := client.GetPersonalAccessToken(
		context.Background(), args, "newtoken", &[]string{"api"}, "",
	)
	require.NoError(t, err)
	response := &Response{true, "YXuxvUgCEmeePY3G1YAa", []string{"api"}, "", ""}
	require.Equal(t, response, result)
}

func TestMissingUser(t *testing.T) {
	client := setup(t)

	args := &commandargs.Shell{GitlabKeyId: "1"}
	_, err := client.GetPersonalAccessToken(
		context.Background(), args, "newtoken", &[]string{"api"}, "",
	)
	require.Equal(t, "missing user", err.Error())
}

func TestErrorResponses(t *testing.T) {
	client := setup(t)

	testCases := []struct {
		desc          string
		fakeId        string
		expectedError string
	}{
		{
			desc:          "A response with an error message",
			fakeId:        "2",
			expectedError: "Not allowed!",
		},
		{
			desc:          "A response with bad JSON",
			fakeId:        "3",
			expectedError: "Parsing failed",
		},
		{
			desc:          "An error response without message",
			fakeId:        "4",
			expectedError: "Internal API error (403)",
		},
	}

	for _, tc := range testCases {
		t.Run(tc.desc, func(t *testing.T) {
			args := &commandargs.Shell{GitlabKeyId: tc.fakeId}
			resp, err := client.GetPersonalAccessToken(
				context.Background(), args, "newtoken", &[]string{"api"}, "",
			)

			require.EqualError(t, err, tc.expectedError)
			require.Nil(t, resp)
		})
	}
}

func setup(t *testing.T) *Client {
	initialize(t)
	url := testserver.StartSocketHttpServer(t, requests)

	client, err := NewClient(&config.Config{GitlabUrl: url})
	require.NoError(t, err)

	return client
}