summaryrefslogtreecommitdiff
path: root/pkg/web/register_test.go
blob: 25700c04e248b65151c8a95f97318a4ac0ccf2c3 (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
package web

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"mokhan.ca/xlgmokha/oauth/pkg/dto"
)

func TestRegister(t *testing.T) {
	srv := NewHttpContext("https://example.com", []byte{})

	t.Run("POST /register", func(t *testing.T) {
		t.Run("with a valid request body", func(t *testing.T) {
			w := httptest.NewRecorder()

			r := httptest.NewRequest("POST", "/register", strings.NewReader(`{
					"redirect_uris": ["https://client.example.org/callback"],
					"client_name": "My Client",
					"token_endpoint_auth_method": "client_secret_basic",
					"logo_uri": "https://client.example.org/logo.png",
					"jwks_uri": "https://client.example.org/my_public_keys.jwks"
				}`,
			))
			r.Header.Set("Content-Type", "application/json")
			r.Header.Set("Accept", "application/json")

			srv.Router().ServeHTTP(w, r)

			assert.Equal(t, http.StatusCreated, w.Result().StatusCode)
			assert.Equal(t, "application/json", w.HeaderMap.Get("Content-Type"))
			assert.Equal(t, "no-store", w.HeaderMap.Get("Cache-Control"))
			assert.Equal(t, "no-cache", w.HeaderMap.Get("Pragma"))

			var x dto.ClientInformationResponse
			json.NewDecoder(w.Body).Decode(&x)

			assert.Equal(t, "My Client", x.ClientName)
			assert.Equal(t, dto.ClientSecretBasic, x.TokenEndpointAuthMethod)
			assert.Equal(t, "https://client.example.org/callback", x.RedirectUris[0])
			assert.Equal(t, "https://client.example.org/logo.png", x.LogoUri)
			assert.Equal(t, "https://client.example.org/my_public_keys.jwks", x.JWKSUri)
			assert.Equal(t, 1, len(x.RedirectUris))
			assert.NotEmpty(t, x.ClientId)
			assert.NotEmpty(t, x.ClientIdIssuedAt)
			assert.NotEmpty(t, x.ClientSecret)
			assert.NotEmpty(t, x.ClientSecretExpiresAt)
		})

		t.Run("with an invalid request body", func(t *testing.T) {
			w := httptest.NewRecorder()

			body := `{"redirect_uris": ["], "client_name": "", "token_endpoint_auth_method": ""}`
			r := httptest.NewRequest("POST", "/register", strings.NewReader(body))
			r.Header.Set("Content-Type", "application/json")
			r.Header.Set("Accept", "application/json")

			srv.Router().ServeHTTP(w, r)

			assert.Equal(t, "application/json", w.HeaderMap.Get("Content-Type"))
			assert.Equal(t, "no-store", w.HeaderMap.Get("Cache-Control"))
			assert.Equal(t, "no-cache", w.HeaderMap.Get("Pragma"))
			assert.Equal(t, http.StatusBadRequest, w.Result().StatusCode)

			var params map[string]string
			json.NewDecoder(w.Body).Decode(&params)

			assert.Equal(t, "invalid_client_metadata", params["error"])
			assert.NotEmpty(t, params["error_description"])
		})
	})
}