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
|
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/db"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/oidc"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
)
func TestUser(t *testing.T) {
repository := db.NewRepository[*domain.User]()
middleware := User(repository)
knownUser := &domain.User{ID: domain.ID(pls.GenerateULID())}
require.NoError(t, repository.Save(knownUser))
t.Run("when ID Token is provided", func(t *testing.T) {
t.Run("when user is known", func(t *testing.T) {
server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := cfg.CurrentUser.From(r.Context())
require.NotNil(t, user)
assert.Equal(t, knownUser.ID, user.ID)
w.WriteHeader(http.StatusTeapot)
}))
ctx := cfg.IDToken.With(t.Context(), &oidc.IDToken{Subject: knownUser.ID.String()})
r, w := test.RequestResponse("GET", "/example", test.WithContext(ctx))
server.ServeHTTP(w, r)
assert.Equal(t, http.StatusTeapot, w.Code)
})
t.Run("when user is unknown", func(t *testing.T) {
unknownID := pls.GenerateULID()
server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := cfg.CurrentUser.From(r.Context())
require.NotNil(t, user)
assert.Equal(t, domain.ID(unknownID), user.ID)
w.WriteHeader(http.StatusTeapot)
}))
ctx := cfg.IDToken.With(t.Context(), &oidc.IDToken{Subject: unknownID})
r, w := test.RequestResponse("GET", "/example", test.WithContext(ctx))
server.ServeHTTP(w, r)
assert.Equal(t, http.StatusTeapot, w.Code)
require.NotNil(t, repository.Find(domain.ID(unknownID)))
})
})
t.Run("when ID Token is not provided", func(t *testing.T) {
server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := cfg.CurrentUser.From(r.Context())
require.Nil(t, user)
w.WriteHeader(http.StatusTeapot)
}))
r, w := test.RequestResponse("GET", "/example")
server.ServeHTTP(w, r)
assert.Equal(t, http.StatusTeapot, w.Code)
})
}
|