summaryrefslogtreecommitdiff
path: root/internal/sshd/sshd_test.go
blob: e5f61113957faafedc11250ed9180a2abe6f2fd9 (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
package sshd

import (
	"context"
	"net/http/httptest"
	"path"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"gitlab.com/gitlab-org/gitlab-shell/client/testserver"
	"gitlab.com/gitlab-org/gitlab-shell/internal/config"
	"gitlab.com/gitlab-org/gitlab-shell/internal/testhelper"
)

const serverUrl = "127.0.0.1:50000"

func TestShutdown(t *testing.T) {
	s := setupServer(t)

	go func() { require.NoError(t, s.ListenAndServe(context.Background())) }()

	verifyStatus(t, s, StatusReady)

	s.wg.Add(1)

	require.NoError(t, s.Shutdown())
	verifyStatus(t, s, StatusOnShutdown)

	s.wg.Done()

	verifyStatus(t, s, StatusClosed)
}

func TestReadinessProbe(t *testing.T) {
	s := &Server{Config: &config.Config{Server: config.DefaultServerConfig}}

	require.Equal(t, StatusStarting, s.getStatus())

	mux := s.MonitoringServeMux()

	req := httptest.NewRequest("GET", "/start", nil)

	r := httptest.NewRecorder()
	mux.ServeHTTP(r, req)
	require.Equal(t, 503, r.Result().StatusCode)

	s.changeStatus(StatusReady)

	r = httptest.NewRecorder()
	mux.ServeHTTP(r, req)
	require.Equal(t, 200, r.Result().StatusCode)

	s.changeStatus(StatusOnShutdown)

	r = httptest.NewRecorder()
	mux.ServeHTTP(r, req)
	require.Equal(t, 503, r.Result().StatusCode)
}

func TestLivenessProbe(t *testing.T) {
	s := &Server{Config: &config.Config{Server: config.DefaultServerConfig}}
	mux := s.MonitoringServeMux()

	req := httptest.NewRequest("GET", "/health", nil)

	r := httptest.NewRecorder()
	mux.ServeHTTP(r, req)
	require.Equal(t, 200, r.Result().StatusCode)
}

func setupServer(t *testing.T) *Server {
	testhelper.PrepareTestRootDir(t)

	url := testserver.StartSocketHttpServer(t, []testserver.TestRequestHandler{})
	srvCfg := config.ServerConfig{
		Listen:       serverUrl,
		HostKeyFiles: []string{path.Join(testhelper.TestRoot, "certs/valid/server.key")},
	}

	cfg := &config.Config{RootDir: "/tmp", GitlabUrl: url, Server: srvCfg}

	return &Server{Config: cfg}
}

func verifyStatus(t *testing.T, s *Server, st status) {
	for i := 5; i < 500; i += 50 {
		if s.getStatus() == st {
			break
		}

		// Sleep incrementally ~2s in total
		time.Sleep(time.Duration(i) * time.Millisecond)
	}

	require.Equal(t, s.getStatus(), st)
}