summaryrefslogtreecommitdiff
path: root/app/middleware/user_test.go
blob: c778c982f1d6e33c2a05340a3c5ed065e0eef374 (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
package middleware

import (
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/xlgmokha/x/pkg/test"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/cfg"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain"
)

func TestUser(t *testing.T) {
	middleware := User()

	t.Run("when x-id-jwt-claim-* headers are not provided", func(t *testing.T) {
		server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			require.False(t, IsLoggedIn(r))

			w.WriteHeader(http.StatusTeapot)
		}))

		r, w := test.RequestResponse("GET", "/example")
		server.ServeHTTP(w, r)

		assert.Equal(t, http.StatusTeapot, w.Code)
	})

	t.Run("when x-id-jwt-claim-* headers are provided", func(t *testing.T) {
		server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			require.True(t, IsLoggedIn(r))

			user := cfg.CurrentUser.From(r.Context())
			require.NotNil(t, user)

			assert.Equal(t, domain.ID("1"), user.ID)
			assert.Equal(t, "root", user.Username)
			assert.Equal(t, "https://gitlab.com/tanuki", user.ProfileURL)
			assert.Equal(t, "https://example.com/profile.png", user.Picture)

			w.WriteHeader(http.StatusTeapot)
		}))

		r, w := test.RequestResponse("GET", "/",
			test.WithRequestHeader("x-id-jwt-claim-sub", "1"),
			test.WithRequestHeader("x-id-jwt-claim-username", "root"),
			test.WithRequestHeader("x-id-jwt-claim-profile-url", "https://gitlab.com/tanuki"),
			test.WithRequestHeader("x-id-jwt-claim-picture-url", "https://example.com/profile.png"),
		)
		server.ServeHTTP(w, r)

		assert.Equal(t, http.StatusTeapot, w.Code)
	})
}