File: web_chooser_test.go

package info (click to toggle)
golang-github-openpubkey-openpubkey 0.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 964 kB
  • sloc: makefile: 10
file content (196 lines) | stat: -rw-r--r-- 6,648 bytes parent folder | download
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// Copyright 2025 OpenPubkey
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

package choosers

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

	"github.com/openpubkey/openpubkey/providers"
	"github.com/stretchr/testify/require"
)

func CreateServerToHandleRedirect(t *testing.T, gotRedirect *bool) (*httptest.Server, string) {
	mux := http.NewServeMux()
	mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
		*gotRedirect = true
		w.WriteHeader(http.StatusOK)
	})
	mockServer := httptest.NewUnstartedServer(mux)
	mockServer.Start()
	return mockServer, mockServer.URL + "/redirect"
}

func TestGoogleSelection(t *testing.T) {
	t.Parallel()
	testCases := []struct {
		name             string
		providerName     string
		issuerPrefix     string
		httpCodeExpected int
		errorString      string
	}{
		{name: "select google", providerName: "google", httpCodeExpected: http.StatusOK},
		{name: "select azure", providerName: "azure", httpCodeExpected: http.StatusOK},
		{name: "select gitlab", providerName: "gitlab", httpCodeExpected: http.StatusOK},
		{name: "select hello", providerName: "hello", httpCodeExpected: http.StatusOK},
		{name: "select bad provider", providerName: "fakeProvider", httpCodeExpected: http.StatusBadRequest, errorString: "unknown OpenID Provider"},
		{name: "select no provider", providerName: "", httpCodeExpected: http.StatusBadRequest, errorString: "missing op parameter"},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			googleOpOptions := providers.GetDefaultGoogleOpOptions()
			googleOp := providers.NewGoogleOpWithOptions(googleOpOptions)

			azureOpOptions := providers.GetDefaultAzureOpOptions()
			azureOp := providers.NewAzureOpWithOptions(azureOpOptions)

			gitlabOpOptions := providers.GetDefaultGitlabOpOptions()
			gitlabOp := providers.NewGitlabOpWithOptions(gitlabOpOptions)

			helloOpOptions := providers.GetDefaultHelloOpOptions()
			helloOp := providers.NewHelloOpWithOptions(helloOpOptions)

			webChooser := WebChooser{
				OpList: []providers.BrowserOpenIdProvider{
					googleOp, azureOp, gitlabOp, helloOp,
				},
				OpenBrowser:   false,
				useMockServer: true,
			}

			var chooserErr error
			var op providers.OpenIdProvider

			gotRedirect := false
			redirectServer, redirectUri := CreateServerToHandleRedirect(t, &gotRedirect)

			testRunDone := make(chan struct{})
			go func() {
				defer close(testRunDone)
				defer redirectServer.Close()

				// If something goes wrong in this go func, this unittest will hang
				// until it times out. If you are running into such an issue
				// check if check if anything here is failing.
				op, chooserErr = webChooser.ChooseOp(context.Background())
				if tc.errorString != "" {
					require.ErrorContains(t, chooserErr, tc.errorString)
					require.Nil(t, op)
					return
				}
				require.NoError(t, chooserErr)
				require.NotNil(t, op)

				// trigger the redirect so the HTTP GET below will complete
				switch tc.providerName {
				case "google":
					googleOp.(*providers.GoogleOp).TriggerBrowserWindowHook(redirectUri)
				case "azure":
					azureOp.(*providers.AzureOp).TriggerBrowserWindowHook(redirectUri)
				case "gitlab":
					gitlabOp.(*providers.GitlabOp).TriggerBrowserWindowHook(redirectUri)
				case "hello":
					helloOp.(*providers.HelloOp).TriggerBrowserWindowHook(redirectUri)
				default:
					// Trigger azure even if the provider doesn't match to sure this test finishes
					azureOp.(*providers.StandardOp).TriggerBrowserWindowHook(redirectUri)
				}

				require.Eventually(t,
					func() bool { return gotRedirect },
					100*time.Millisecond, 1*time.Millisecond, "redirect not triggered but should have been",
				)
			}()

			// Wait until the server is listening
			require.Eventually(t, func() bool {
				return chooserErr != nil || webChooser.mockServer != nil && webChooser.mockServer.URL != ""
			}, 3*time.Second, 100*time.Millisecond)

			if chooserErr != nil {
				if tc.errorString != "" {
					require.ErrorContains(t, chooserErr, tc.errorString)
				} else {
					require.NoError(t, chooserErr)
				}
			}

			// Make a request to the server to trigger Google selection and get redirect
			resp, err := http.Get(webChooser.mockServer.URL + "/select?op=" + tc.providerName)
			if tc.httpCodeExpected != http.StatusOK {
				require.Equal(t, tc.httpCodeExpected, resp.StatusCode)
			} else {
				require.NoError(t, err)
				require.Equal(t, http.StatusOK, resp.StatusCode)

				op, err = webChooser.ChooseOp(context.Background())
				require.ErrorContains(t, err, "provider has already been chosen")
				require.Nil(t, op)
			}

			// Since we use a go func inside the test, we need to ensure it finishes before we move on to the next test
			select {
			case <-testRunDone:
				require.Nil(t, nil)
			case <-time.After(5 * time.Second):
				t.Fatal("test timed out")
			}
		})
	}

}

func TestDuplicateProviderError(t *testing.T) {
	googleOpOptions := providers.GetDefaultGoogleOpOptions()
	googleOp := providers.NewGoogleOpWithOptions(googleOpOptions)

	webChooser := WebChooser{
		OpList:        []providers.BrowserOpenIdProvider{googleOp, googleOp},
		OpenBrowser:   false,
		useMockServer: true,
	}
	op, err := webChooser.ChooseOp(context.Background())
	require.ErrorContains(t, err, "provider in web chooser found with duplicate issuer: https://accounts.google.com")
	require.Nil(t, op)
}

func TestIssuerToName(t *testing.T) {
	name, err := IssuerToName("https://accounts.google.com")
	require.NoError(t, err)
	require.Equal(t, "google", name)

	name, err = IssuerToName("https://login.microsoftonline.com")
	require.NoError(t, err)
	require.Equal(t, "azure", name)

	name, err = IssuerToName("https://gitlab.com")
	require.NoError(t, err)
	require.Equal(t, "gitlab", name)

	name, err = IssuerToName("https://noterror.example.com")
	require.NoError(t, err)
	require.Equal(t, "noterror.example.com", name)

	name, err = IssuerToName("error.example.com")
	require.ErrorContains(t, err, "invalid OpenID Provider issuer: error.example.com")
	require.Equal(t, "", name)
}