summaryrefslogtreecommitdiff
path: root/internal/command/shared/accessverifier/accessverifier_test.go
blob: 8e0b5f91fe606a1d3f2fc9038ea8a552f4447e8f (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
package accessverifier

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

	"github.com/stretchr/testify/require"

	"gitlab.com/gitlab-org/gitlab-shell/client/testserver"
	"gitlab.com/gitlab-org/gitlab-shell/internal/command/commandargs"
	"gitlab.com/gitlab-org/gitlab-shell/internal/command/readwriter"
	"gitlab.com/gitlab-org/gitlab-shell/internal/config"
	"gitlab.com/gitlab-org/gitlab-shell/internal/gitlabnet/accessverifier"
)

var (
	repo   = "group/repo"
	action = commandargs.ReceivePack
)

func setup(t *testing.T) (*Command, *bytes.Buffer, *bytes.Buffer) {
	requests := []testserver.TestRequestHandler{
		{
			Path: "/api/v4/internal/allowed",
			Handler: func(w http.ResponseWriter, r *http.Request) {
				b, err := ioutil.ReadAll(r.Body)
				require.NoError(t, err)

				var requestBody *accessverifier.Request
				err = json.Unmarshal(b, &requestBody)
				require.NoError(t, err)

				if requestBody.KeyId == "1" {
					body := map[string]interface{}{
						"gl_console_messages": []string{"console", "message"},
					}
					require.NoError(t, json.NewEncoder(w).Encode(body))
				} else {
					body := map[string]interface{}{
						"status":  false,
						"message": "missing user",
					}
					require.NoError(t, json.NewEncoder(w).Encode(body))
				}
			},
		},
	}

	url := testserver.StartSocketHttpServer(t, requests)

	errBuf := &bytes.Buffer{}
	outBuf := &bytes.Buffer{}

	readWriter := &readwriter.ReadWriter{Out: outBuf, ErrOut: errBuf}
	cmd := &Command{Config: &config.Config{GitlabUrl: url}, ReadWriter: readWriter}

	return cmd, errBuf, outBuf
}

func TestMissingUser(t *testing.T) {
	cmd, _, _ := setup(t)

	cmd.Args = &commandargs.Shell{GitlabKeyId: "2"}
	_, err := cmd.Verify(context.Background(), action, repo)

	require.Equal(t, "missing user", err.Error())
}

func TestConsoleMessages(t *testing.T) {
	cmd, errBuf, outBuf := setup(t)

	cmd.Args = &commandargs.Shell{GitlabKeyId: "1"}
	cmd.Verify(context.Background(), action, repo)

	require.Equal(t, "remote: \nremote: console\nremote: message\nremote: \n", errBuf.String())
	require.Empty(t, outBuf.String())
}