mirror of
https://github.com/vmware-tanzu/pinniped.git
synced 2026-09-06 08:07:08 +00:00
Replace agouti and chromedriver with chromedp across the whole project
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved.
|
||||
// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
package integration
|
||||
|
||||
@@ -280,7 +280,7 @@ func runPinnipedLoginOIDC(
|
||||
sessionCachePath := testutil.TempDir(t) + "/sessions.yaml"
|
||||
|
||||
// Start the browser driver.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
// Start the CLI running the "login oidc [...]" command with stdout/stderr connected to pipes.
|
||||
cmd := oidcLoginCommand(ctx, t, pinnipedExe, sessionCachePath)
|
||||
@@ -334,22 +334,21 @@ func runPinnipedLoginOIDC(
|
||||
case loginURL = <-loginURLChan:
|
||||
}
|
||||
t.Logf("navigating to login page")
|
||||
require.NoError(t, page.Navigate(loginURL))
|
||||
browser.Navigate(t, loginURL)
|
||||
|
||||
// Expect to be redirected to the upstream provider and log in.
|
||||
browsertest.LoginToUpstreamOIDC(t, page, env.CLIUpstreamOIDC)
|
||||
browsertest.LoginToUpstreamOIDC(t, browser, env.CLIUpstreamOIDC)
|
||||
|
||||
// Expect to be redirected to the localhost callback.
|
||||
t.Logf("waiting for redirect to callback")
|
||||
callbackURLPattern := regexp.MustCompile(`\A` + regexp.QuoteMeta(env.CLIUpstreamOIDC.CallbackURL) + `(\?.+)?\z`)
|
||||
browsertest.WaitForURL(t, page, callbackURLPattern)
|
||||
browser.WaitForURL(t, callbackURLPattern)
|
||||
|
||||
// Wait for the "pre" element that gets rendered for a `text/plain` page, and
|
||||
// assert that it contains the success message.
|
||||
t.Logf("verifying success page")
|
||||
browsertest.WaitForVisibleElements(t, page, "pre")
|
||||
msg, err := page.First("pre").Text()
|
||||
require.NoError(t, err)
|
||||
browser.WaitForVisibleElements(t, "pre")
|
||||
msg := browser.TextOfFirstMatch(t, "pre")
|
||||
require.Equal(t, "you have been logged in and may now close this tab", msg)
|
||||
|
||||
// Expect the CLI to output an ExecCredential in JSON format.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved.
|
||||
// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
package integration
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/creack/pty"
|
||||
"github.com/sclevine/agouti"
|
||||
"github.com/stretchr/testify/require"
|
||||
authorizationv1 "k8s.io/api/authorization/v1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
@@ -123,7 +122,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
tempDir := testutil.TempDir(t) // per-test tmp dir to avoid sharing files between tests
|
||||
|
||||
// Start a fresh browser driver because we don't want to share cookies between the various tests in this file.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
expectedUsername := env.SupervisorUpstreamOIDC.Username
|
||||
expectedGroups := env.SupervisorUpstreamOIDC.ExpectedGroups
|
||||
@@ -177,18 +176,18 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...)
|
||||
|
||||
// Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser.
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, page)
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser)
|
||||
|
||||
// Confirm that we got to the upstream IDP's login page, fill out the form, and submit the form.
|
||||
browsertest.LoginToUpstreamOIDC(t, page, env.SupervisorUpstreamOIDC)
|
||||
browsertest.LoginToUpstreamOIDC(t, browser, env.SupervisorUpstreamOIDC)
|
||||
|
||||
// Expect to be redirected to the downstream callback which is serving the form_post HTML.
|
||||
t.Logf("waiting for response page %s", downstream.Spec.Issuer)
|
||||
browsertest.WaitForURL(t, page, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
browser.WaitForURL(t, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
|
||||
// The response page should have done the background fetch() and POST'ed to the CLI's callback.
|
||||
// It should now be in the "success" state.
|
||||
formpostExpectSuccessState(t, page)
|
||||
formpostExpectSuccessState(t, browser)
|
||||
|
||||
requireKubectlGetNamespaceOutput(t, env, waitForKubectlOutput(t, kubectlOutputChan))
|
||||
|
||||
@@ -204,7 +203,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
tempDir := testutil.TempDir(t) // per-test tmp dir to avoid sharing files between tests
|
||||
|
||||
// Start a fresh browser driver because we don't want to share cookies between the various tests in this file.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
expectedUsername := env.SupervisorUpstreamOIDC.Username
|
||||
expectedGroups := env.SupervisorUpstreamOIDC.ExpectedGroups
|
||||
@@ -258,18 +257,18 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...)
|
||||
|
||||
// Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser.
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, page)
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser)
|
||||
|
||||
// Confirm that we got to the upstream IDP's login page, fill out the form, and submit the form.
|
||||
browsertest.LoginToUpstreamOIDC(t, page, env.SupervisorUpstreamOIDC)
|
||||
browsertest.LoginToUpstreamOIDC(t, browser, env.SupervisorUpstreamOIDC)
|
||||
|
||||
// Expect to be redirected to the downstream callback which is serving the form_post HTML.
|
||||
t.Logf("waiting for response page %s", downstream.Spec.Issuer)
|
||||
browsertest.WaitForURL(t, page, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
browser.WaitForURL(t, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
|
||||
// The response page should have done the background fetch() and POST'ed to the CLI's callback.
|
||||
// It should now be in the "success" state.
|
||||
formpostExpectSuccessState(t, page)
|
||||
formpostExpectSuccessState(t, browser)
|
||||
|
||||
requireKubectlGetNamespaceOutput(t, env, waitForKubectlOutput(t, kubectlOutputChan))
|
||||
|
||||
@@ -288,7 +287,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
tempDir := testutil.TempDir(t) // per-test tmp dir to avoid sharing files between tests
|
||||
|
||||
// Start a fresh browser driver because we don't want to share cookies between the various tests in this file.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
expectedUsername := env.SupervisorUpstreamOIDC.Username
|
||||
expectedGroups := env.SupervisorUpstreamOIDC.ExpectedGroups
|
||||
@@ -363,20 +362,20 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
require.NotEmptyf(t, loginURL, "didn't find login URL in output: %s", output)
|
||||
|
||||
t.Logf("navigating to login page")
|
||||
require.NoError(t, page.Navigate(loginURL))
|
||||
browser.Navigate(t, loginURL)
|
||||
|
||||
// Expect to be redirected to the upstream provider and log in.
|
||||
browsertest.LoginToUpstreamOIDC(t, page, env.SupervisorUpstreamOIDC)
|
||||
browsertest.LoginToUpstreamOIDC(t, browser, env.SupervisorUpstreamOIDC)
|
||||
|
||||
// Expect to be redirected to the downstream callback which is serving the form_post HTML.
|
||||
t.Logf("waiting for response page %s", downstream.Spec.Issuer)
|
||||
browsertest.WaitForURL(t, page, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
browser.WaitForURL(t, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
|
||||
// The response page should have failed to automatically post, and should now be showing the manual instructions.
|
||||
authCode := formpostExpectManualState(t, page)
|
||||
authCode := formpostExpectManualState(t, browser)
|
||||
|
||||
// Enter the auth code in the waiting prompt, followed by a newline.
|
||||
t.Logf("'manually' pasting authorization code %q to waiting prompt", authCode)
|
||||
t.Logf("'manually' pasting authorization code with length %d to waiting prompt", len(authCode))
|
||||
_, err = ptyFile.WriteString(authCode + "\n")
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -399,7 +398,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
tempDir := testutil.TempDir(t) // per-test tmp dir to avoid sharing files between tests
|
||||
|
||||
// Start a fresh browser driver because we don't want to share cookies between the various tests in this file.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
expectedUsername := env.SupervisorUpstreamOIDC.Username
|
||||
expectedGroups := env.SupervisorUpstreamOIDC.ExpectedGroups
|
||||
@@ -488,20 +487,20 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
require.NotEmptyf(t, loginURL, "didn't find login URL in output: %s", output)
|
||||
|
||||
t.Logf("navigating to login page")
|
||||
require.NoError(t, page.Navigate(loginURL))
|
||||
browser.Navigate(t, loginURL)
|
||||
|
||||
// Expect to be redirected to the upstream provider and log in.
|
||||
browsertest.LoginToUpstreamOIDC(t, page, env.SupervisorUpstreamOIDC)
|
||||
browsertest.LoginToUpstreamOIDC(t, browser, env.SupervisorUpstreamOIDC)
|
||||
|
||||
// Expect to be redirected to the downstream callback which is serving the form_post HTML.
|
||||
t.Logf("waiting for response page %s", downstream.Spec.Issuer)
|
||||
browsertest.WaitForURL(t, page, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
browser.WaitForURL(t, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
|
||||
// The response page should have failed to automatically post, and should now be showing the manual instructions.
|
||||
authCode := formpostExpectManualState(t, page)
|
||||
authCode := formpostExpectManualState(t, browser)
|
||||
|
||||
// Enter the auth code in the waiting prompt, followed by a newline.
|
||||
t.Logf("'manually' pasting authorization code %q to waiting prompt", authCode)
|
||||
t.Logf("'manually' pasting authorization code with length %d to waiting prompt", len(authCode))
|
||||
_, err = ptyFile.WriteString(authCode + "\n")
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -1002,7 +1001,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
tempDir := testutil.TempDir(t) // per-test tmp dir to avoid sharing files between tests
|
||||
|
||||
// Start a fresh browser driver because we don't want to share cookies between the various tests in this file.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
expectedUsername := env.SupervisorUpstreamLDAP.TestUserMailAttributeValue
|
||||
expectedGroups := env.SupervisorUpstreamLDAP.TestUserDirectGroupsDNs
|
||||
@@ -1029,13 +1028,13 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...)
|
||||
|
||||
// Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser.
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, page)
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser)
|
||||
|
||||
// Confirm that we got to the Supervisor's login page, fill out the form, and submit the form.
|
||||
browsertest.LoginToUpstreamLDAP(t, page, downstream.Spec.Issuer,
|
||||
browsertest.LoginToUpstreamLDAP(t, browser, downstream.Spec.Issuer,
|
||||
expectedUsername, env.SupervisorUpstreamLDAP.TestUserPassword)
|
||||
|
||||
formpostExpectSuccessState(t, page)
|
||||
formpostExpectSuccessState(t, browser)
|
||||
|
||||
requireKubectlGetNamespaceOutput(t, env, waitForKubectlOutput(t, kubectlOutputChan))
|
||||
|
||||
@@ -1052,7 +1051,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
tempDir := testutil.TempDir(t) // per-test tmp dir to avoid sharing files between tests
|
||||
|
||||
// Start a fresh browser driver because we don't want to share cookies between the various tests in this file.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
expectedUsername := env.SupervisorUpstreamActiveDirectory.TestUserPrincipalNameValue
|
||||
expectedGroups := env.SupervisorUpstreamActiveDirectory.TestUserIndirectGroupsSAMAccountPlusDomainNames
|
||||
@@ -1079,13 +1078,13 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...)
|
||||
|
||||
// Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser.
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, page)
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser)
|
||||
|
||||
// Confirm that we got to the Supervisor's login page, fill out the form, and submit the form.
|
||||
browsertest.LoginToUpstreamLDAP(t, page, downstream.Spec.Issuer,
|
||||
browsertest.LoginToUpstreamLDAP(t, browser, downstream.Spec.Issuer,
|
||||
expectedUsername, env.SupervisorUpstreamActiveDirectory.TestUserPassword)
|
||||
|
||||
formpostExpectSuccessState(t, page)
|
||||
formpostExpectSuccessState(t, browser)
|
||||
|
||||
requireKubectlGetNamespaceOutput(t, env, waitForKubectlOutput(t, kubectlOutputChan))
|
||||
|
||||
@@ -1102,7 +1101,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
tempDir := testutil.TempDir(t) // per-test tmp dir to avoid sharing files between tests
|
||||
|
||||
// Start a fresh browser driver because we don't want to share cookies between the various tests in this file.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
expectedUsername := env.SupervisorUpstreamLDAP.TestUserMailAttributeValue
|
||||
expectedGroups := env.SupervisorUpstreamLDAP.TestUserDirectGroupsDNs
|
||||
@@ -1135,13 +1134,13 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...)
|
||||
|
||||
// Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser.
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, page)
|
||||
kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser)
|
||||
|
||||
// Confirm that we got to the Supervisor's login page, fill out the form, and submit the form.
|
||||
browsertest.LoginToUpstreamLDAP(t, page, downstream.Spec.Issuer,
|
||||
browsertest.LoginToUpstreamLDAP(t, browser, downstream.Spec.Issuer,
|
||||
expectedUsername, env.SupervisorUpstreamLDAP.TestUserPassword)
|
||||
|
||||
formpostExpectSuccessState(t, page)
|
||||
formpostExpectSuccessState(t, browser)
|
||||
|
||||
requireKubectlGetNamespaceOutput(t, env, waitForKubectlOutput(t, kubectlOutputChan))
|
||||
|
||||
@@ -1149,7 +1148,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func startKubectlAndOpenAuthorizationURLInBrowser(testCtx context.Context, t *testing.T, kubectlCmd *exec.Cmd, page *agouti.Page) chan string {
|
||||
func startKubectlAndOpenAuthorizationURLInBrowser(testCtx context.Context, t *testing.T, kubectlCmd *exec.Cmd, b *browsertest.Browser) chan string {
|
||||
// Wrap the stdout and stderr pipes with TeeReaders which will copy each incremental read to an
|
||||
// in-memory buffer, so we can have the full output available to us at the end.
|
||||
originalStderrPipe, err := kubectlCmd.StderrPipe()
|
||||
@@ -1226,7 +1225,7 @@ func startKubectlAndOpenAuthorizationURLInBrowser(testCtx context.Context, t *te
|
||||
case loginURL = <-loginURLChan:
|
||||
}
|
||||
t.Logf("navigating to login page: %q", loginURL)
|
||||
require.NoError(t, page.Navigate(loginURL))
|
||||
b.Navigate(t, loginURL)
|
||||
|
||||
return kubectlOutputChan
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved.
|
||||
// Copyright 2021-2023 the Pinniped contributors. All Rights Reserved.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package integration
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
|
||||
"github.com/ory/fosite"
|
||||
"github.com/ory/fosite/token/hmac"
|
||||
"github.com/sclevine/agouti"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
@@ -33,24 +32,25 @@ func TestFormPostHTML_Browser_Parallel(t *testing.T) {
|
||||
// Run a mock callback handler, simulating the one running in the CLI.
|
||||
callbackURL, expectCallback := formpostCallbackServer(t)
|
||||
|
||||
// Open a single browser for all subtests to use (in sequence).
|
||||
page := browsertest.Open(t)
|
||||
|
||||
t.Run("success", func(t *testing.T) {
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
// Serve the form_post template with successful parameters.
|
||||
responseParams := formpostRandomParams(t)
|
||||
formpostInitiate(t, page, formpostTemplateServer(t, callbackURL, responseParams))
|
||||
formpostInitiate(t, browser, formpostTemplateServer(t, callbackURL, responseParams))
|
||||
|
||||
// Now we handle the callback and assert that we got what we expected. This should transition
|
||||
// the UI into the success state.
|
||||
expectCallback(t, responseParams)
|
||||
formpostExpectSuccessState(t, page)
|
||||
formpostExpectSuccessState(t, browser)
|
||||
})
|
||||
|
||||
t.Run("callback server error", func(t *testing.T) {
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
// Serve the form_post template with a redirect URI that will return an HTTP 500 response.
|
||||
responseParams := formpostRandomParams(t)
|
||||
formpostInitiate(t, page, formpostTemplateServer(t, callbackURL+"?fail=500", responseParams))
|
||||
formpostInitiate(t, browser, formpostTemplateServer(t, callbackURL+"?fail=500", responseParams))
|
||||
|
||||
// Now we handle the callback and assert that we got what we expected.
|
||||
expectCallback(t, responseParams)
|
||||
@@ -66,13 +66,15 @@ func TestFormPostHTML_Browser_Parallel(t *testing.T) {
|
||||
// In the future, we could change the Javascript code to use mode 'cors'
|
||||
// because we have upgraded our CLI callback endpoint to handle CORS,
|
||||
// and then we could change this to formpostExpectManualState().
|
||||
formpostExpectSuccessState(t, page)
|
||||
formpostExpectSuccessState(t, browser)
|
||||
})
|
||||
|
||||
t.Run("network failure", func(t *testing.T) {
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
// Serve the form_post template with a redirect URI that will return a network error.
|
||||
responseParams := formpostRandomParams(t)
|
||||
formpostInitiate(t, page, formpostTemplateServer(t, callbackURL+"?fail=close", responseParams))
|
||||
formpostInitiate(t, browser, formpostTemplateServer(t, callbackURL+"?fail=close", responseParams))
|
||||
|
||||
// Now we handle the callback and assert that we got what we expected.
|
||||
// This will trigger the callback server to close the client connection abruptly because
|
||||
@@ -80,28 +82,30 @@ func TestFormPostHTML_Browser_Parallel(t *testing.T) {
|
||||
expectCallback(t, responseParams)
|
||||
|
||||
// This failure should cause the UI to enter the "manual" state.
|
||||
actualCode := formpostExpectManualState(t, page)
|
||||
actualCode := formpostExpectManualState(t, browser)
|
||||
require.Equal(t, responseParams.Get("code"), actualCode)
|
||||
})
|
||||
|
||||
t.Run("timeout", func(t *testing.T) {
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
// Serve the form_post template with successful parameters.
|
||||
responseParams := formpostRandomParams(t)
|
||||
formpostInitiate(t, page, formpostTemplateServer(t, callbackURL, responseParams))
|
||||
formpostInitiate(t, browser, formpostTemplateServer(t, callbackURL, responseParams))
|
||||
|
||||
// Sleep for longer than the two second timeout.
|
||||
// During this sleep we are blocking the callback from returning.
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// Assert that the timeout fires and we see the manual instructions.
|
||||
actualCode := formpostExpectManualState(t, page)
|
||||
actualCode := formpostExpectManualState(t, browser)
|
||||
require.Equal(t, responseParams.Get("code"), actualCode)
|
||||
|
||||
// Now simulate the callback finally succeeding, in which case
|
||||
// the manual instructions should disappear and we should see the success
|
||||
// div instead.
|
||||
expectCallback(t, responseParams)
|
||||
formpostExpectSuccessState(t, page)
|
||||
formpostExpectSuccessState(t, browser)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -228,88 +232,66 @@ func formpostRandomParams(t *testing.T) url.Values {
|
||||
}
|
||||
}
|
||||
|
||||
// formpostExpectTitle asserts that the page has the expected title.
|
||||
func formpostExpectTitle(t *testing.T, page *agouti.Page, expected string) {
|
||||
// formpostExpectFavicon asserts that the page has the expected SVG/emoji favicon.
|
||||
func formpostExpectFavicon(t *testing.T, b *browsertest.Browser, expected string) {
|
||||
t.Helper()
|
||||
actual, err := page.Title()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
// formpostExpectTitle asserts that the page has the expected SVG/emoji favicon.
|
||||
func formpostExpectFavicon(t *testing.T, page *agouti.Page, expected string) {
|
||||
t.Helper()
|
||||
iconURL, err := page.First("#favicon").Attribute("href")
|
||||
require.NoError(t, err)
|
||||
iconURL := b.AttrValueOfFirstMatch(t, "#favicon", "href")
|
||||
require.True(t, strings.HasPrefix(iconURL, "data:image/svg+xml,<svg"))
|
||||
|
||||
// For some reason chromedriver on Linux returns this attribute urlencoded, but on macOS it contains the
|
||||
// original emoji bytes (unescaped). To check correctly in both cases we allow either version here.
|
||||
expectedEscaped := url.QueryEscape(expected)
|
||||
require.Truef(t,
|
||||
strings.Contains(iconURL, expected) || strings.Contains(iconURL, expectedEscaped),
|
||||
"expected %q to contain %q or %q", iconURL, expected, expectedEscaped,
|
||||
)
|
||||
require.Contains(t, iconURL, expected)
|
||||
}
|
||||
|
||||
// formpostInitiate navigates to the template server endpoint and expects the
|
||||
// loading animation to be shown.
|
||||
func formpostInitiate(t *testing.T, page *agouti.Page, url string) {
|
||||
func formpostInitiate(t *testing.T, b *browsertest.Browser, url string) {
|
||||
t.Helper()
|
||||
require.NoError(t, page.Reset())
|
||||
t.Logf("navigating to mock form_post template URL %s...", url)
|
||||
require.NoError(t, page.Navigate(url))
|
||||
b.Navigate(t, url)
|
||||
|
||||
t.Logf("expecting to see loading animation...")
|
||||
browsertest.WaitForVisibleElements(t, page, "#loading")
|
||||
formpostExpectTitle(t, page, "Logging in...")
|
||||
formpostExpectFavicon(t, page, "⏳")
|
||||
b.WaitForVisibleElements(t, "div#loading")
|
||||
require.Equal(t, "Logging in...", b.Title(t))
|
||||
formpostExpectFavicon(t, b, "⏳")
|
||||
}
|
||||
|
||||
// formpostExpectSuccessState asserts that the page is in the "success" state.
|
||||
func formpostExpectSuccessState(t *testing.T, page *agouti.Page) {
|
||||
func formpostExpectSuccessState(t *testing.T, b *browsertest.Browser) {
|
||||
t.Helper()
|
||||
t.Logf("expecting to see success message become visible...")
|
||||
browsertest.WaitForVisibleElements(t, page, "#success")
|
||||
successDivText, err := page.First("#success").Text()
|
||||
require.NoError(t, err)
|
||||
b.WaitForVisibleElements(t, "div#success")
|
||||
successDivText := b.TextOfFirstMatch(t, "div#success")
|
||||
require.Contains(t, successDivText, "Login succeeded")
|
||||
require.Contains(t, successDivText, "You have successfully logged in. You may now close this tab.")
|
||||
formpostExpectTitle(t, page, "Login succeeded")
|
||||
formpostExpectFavicon(t, page, "✅")
|
||||
require.Equal(t, "Login succeeded", b.Title(t))
|
||||
formpostExpectFavicon(t, b, "✅")
|
||||
}
|
||||
|
||||
// formpostExpectManualState asserts that the page is in the "manual" state and returns the auth code.
|
||||
func formpostExpectManualState(t *testing.T, page *agouti.Page) string {
|
||||
func formpostExpectManualState(t *testing.T, b *browsertest.Browser) string {
|
||||
t.Helper()
|
||||
t.Logf("expecting to see manual message become visible...")
|
||||
browsertest.WaitForVisibleElements(t, page, "#manual")
|
||||
manualDivText, err := page.First("#manual").Text()
|
||||
require.NoError(t, err)
|
||||
b.WaitForVisibleElements(t, "div#manual")
|
||||
manualDivText := b.TextOfFirstMatch(t, "div#manual")
|
||||
require.Contains(t, manualDivText, "Finish your login")
|
||||
require.Contains(t, manualDivText, "To finish logging in, paste this authorization code into your command-line session:")
|
||||
formpostExpectTitle(t, page, "Finish your login")
|
||||
formpostExpectFavicon(t, page, "⌛")
|
||||
require.Equal(t, "Finish your login", b.Title(t))
|
||||
formpostExpectFavicon(t, b, "⌛")
|
||||
|
||||
// Click the copy button and expect that the code is copied to the clipboard. Unfortunately,
|
||||
// headless Chrome does not have a real clipboard we can check, so we rely on checking a
|
||||
// console.log() statement that happens at the same time.
|
||||
t.Logf("clicking the 'copy' button and expecting the clipboard event to fire...")
|
||||
require.NoError(t, page.First("#manual-copy-button").Click())
|
||||
b.ClickFirstMatch(t, "#manual-copy-button")
|
||||
|
||||
var authCode string
|
||||
consoleLogPattern := regexp.MustCompile(`code (.+) to clipboard`)
|
||||
testlib.RequireEventually(t, func(requireEventually *require.Assertions) {
|
||||
logs, err := page.ReadNewLogs("browser")
|
||||
requireEventually.NoError(err)
|
||||
|
||||
for _, log := range logs {
|
||||
if match := consoleLogPattern.FindStringSubmatch(log.Message); match != nil {
|
||||
authCode = match[1]
|
||||
return
|
||||
}
|
||||
matchingText, found := b.FindConsoleEventWithTextMatching("info", consoleLogPattern)
|
||||
requireEventually.True(found)
|
||||
if captureMatches := consoleLogPattern.FindStringSubmatch(matchingText); captureMatches != nil {
|
||||
authCode = captureMatches[1]
|
||||
return
|
||||
}
|
||||
requireEventually.FailNow("expected console log was not found")
|
||||
}, 3*time.Second, 100*time.Millisecond)
|
||||
}, 10*time.Second, 100*time.Millisecond)
|
||||
return authCode
|
||||
}
|
||||
|
||||
@@ -2429,15 +2429,15 @@ func requestAuthorizationAndExpectImmediateRedirectToCallback(t *testing.T, _, d
|
||||
t.Helper()
|
||||
|
||||
// Open the web browser and navigate to the downstream authorize URL.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
t.Logf("opening browser to downstream authorize URL %s", testlib.MaskTokens(downstreamAuthorizeURL))
|
||||
require.NoError(t, page.Navigate(downstreamAuthorizeURL))
|
||||
browser.Navigate(t, downstreamAuthorizeURL)
|
||||
|
||||
// Expect that it immediately redirects back to the callback, which is what happens for certain types of errors
|
||||
// where it is not worth redirecting to the login UI page.
|
||||
t.Logf("waiting for redirect to callback")
|
||||
callbackURLPattern := regexp.MustCompile(`\A` + regexp.QuoteMeta(downstreamCallbackURL) + `\?.+\z`)
|
||||
browsertest.WaitForURL(t, page, callbackURLPattern)
|
||||
browser.WaitForURL(t, callbackURLPattern)
|
||||
}
|
||||
|
||||
func requestAuthorizationUsingBrowserAuthcodeFlowOIDC(t *testing.T, _, downstreamAuthorizeURL, downstreamCallbackURL, _, _ string, httpClient *http.Client) {
|
||||
@@ -2451,17 +2451,17 @@ func requestAuthorizationUsingBrowserAuthcodeFlowOIDC(t *testing.T, _, downstrea
|
||||
makeAuthorizationRequestAndRequireSecurityHeaders(ctx, t, downstreamAuthorizeURL, httpClient)
|
||||
|
||||
// Open the web browser and navigate to the downstream authorize URL.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
t.Logf("opening browser to downstream authorize URL %s", testlib.MaskTokens(downstreamAuthorizeURL))
|
||||
require.NoError(t, page.Navigate(downstreamAuthorizeURL))
|
||||
browser.Navigate(t, downstreamAuthorizeURL)
|
||||
|
||||
// Expect to be redirected to the upstream provider and log in.
|
||||
browsertest.LoginToUpstreamOIDC(t, page, env.SupervisorUpstreamOIDC)
|
||||
browsertest.LoginToUpstreamOIDC(t, browser, env.SupervisorUpstreamOIDC)
|
||||
|
||||
// Wait for the login to happen and us be redirected back to a localhost callback.
|
||||
t.Logf("waiting for redirect to callback")
|
||||
callbackURLPattern := regexp.MustCompile(`\A` + regexp.QuoteMeta(downstreamCallbackURL) + `\?.+\z`)
|
||||
browsertest.WaitForURL(t, page, callbackURLPattern)
|
||||
browser.WaitForURL(t, callbackURLPattern)
|
||||
}
|
||||
|
||||
func requestAuthorizationUsingBrowserAuthcodeFlowLDAP(t *testing.T, downstreamIssuer, downstreamAuthorizeURL, downstreamCallbackURL, username, password string, httpClient *http.Client) {
|
||||
@@ -2474,51 +2474,51 @@ func requestAuthorizationUsingBrowserAuthcodeFlowLDAP(t *testing.T, downstreamIs
|
||||
makeAuthorizationRequestAndRequireSecurityHeaders(ctx, t, downstreamAuthorizeURL, httpClient)
|
||||
|
||||
// Open the web browser and navigate to the downstream authorize URL.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
t.Logf("opening browser to downstream authorize URL %s", testlib.MaskTokens(downstreamAuthorizeURL))
|
||||
require.NoError(t, page.Navigate(downstreamAuthorizeURL))
|
||||
browser.Navigate(t, downstreamAuthorizeURL)
|
||||
|
||||
// Expect to be redirected to the upstream provider and log in.
|
||||
browsertest.LoginToUpstreamLDAP(t, page, downstreamIssuer, username, password)
|
||||
browsertest.LoginToUpstreamLDAP(t, browser, downstreamIssuer, username, password)
|
||||
|
||||
// Wait for the login to happen and us be redirected back to a localhost callback.
|
||||
t.Logf("waiting for redirect to callback")
|
||||
callbackURLPattern := regexp.MustCompile(`\A` + regexp.QuoteMeta(downstreamCallbackURL) + `\?.+\z`)
|
||||
browsertest.WaitForURL(t, page, callbackURLPattern)
|
||||
browser.WaitForURL(t, callbackURLPattern)
|
||||
}
|
||||
|
||||
func requestAuthorizationUsingBrowserAuthcodeFlowLDAPWithBadCredentials(t *testing.T, downstreamIssuer, downstreamAuthorizeURL, _, username, password string, _ *http.Client) {
|
||||
t.Helper()
|
||||
|
||||
// Open the web browser and navigate to the downstream authorize URL.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
t.Logf("opening browser to downstream authorize URL %s", testlib.MaskTokens(downstreamAuthorizeURL))
|
||||
require.NoError(t, page.Navigate(downstreamAuthorizeURL))
|
||||
browser.Navigate(t, downstreamAuthorizeURL)
|
||||
|
||||
// This functions assumes that it has been passed either a bad username or a bad password, and submits the
|
||||
// provided credentials. Expect to be redirected to the upstream provider and attempt to log in.
|
||||
browsertest.LoginToUpstreamLDAP(t, page, downstreamIssuer, username, password)
|
||||
browsertest.LoginToUpstreamLDAP(t, browser, downstreamIssuer, username, password)
|
||||
|
||||
// After failing login expect to land back on the login page again with an error message.
|
||||
browsertest.WaitForUpstreamLDAPLoginPageWithError(t, page, downstreamIssuer)
|
||||
browsertest.WaitForUpstreamLDAPLoginPageWithError(t, browser, downstreamIssuer)
|
||||
}
|
||||
|
||||
func requestAuthorizationUsingBrowserAuthcodeFlowLDAPWithBadCredentialsAndThenGoodCredentials(t *testing.T, downstreamIssuer, downstreamAuthorizeURL, _, username, password string, _ *http.Client) {
|
||||
t.Helper()
|
||||
|
||||
// Open the web browser and navigate to the downstream authorize URL.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
t.Logf("opening browser to downstream authorize URL %s", testlib.MaskTokens(downstreamAuthorizeURL))
|
||||
require.NoError(t, page.Navigate(downstreamAuthorizeURL))
|
||||
browser.Navigate(t, downstreamAuthorizeURL)
|
||||
|
||||
// Expect to be redirected to the upstream provider and attempt to log in.
|
||||
browsertest.LoginToUpstreamLDAP(t, page, downstreamIssuer, username, "this is the wrong password!")
|
||||
browsertest.LoginToUpstreamLDAP(t, browser, downstreamIssuer, username, "this is the wrong password!")
|
||||
|
||||
// After failing login expect to land back on the login page again with an error message.
|
||||
browsertest.WaitForUpstreamLDAPLoginPageWithError(t, page, downstreamIssuer)
|
||||
browsertest.WaitForUpstreamLDAPLoginPageWithError(t, browser, downstreamIssuer)
|
||||
|
||||
// Already at the login page, so this time can directly submit it using the provided username and password.
|
||||
browsertest.SubmitUpstreamLDAPLoginForm(t, page, username, password)
|
||||
browsertest.SubmitUpstreamLDAPLoginForm(t, browser, username, password)
|
||||
}
|
||||
|
||||
func makeAuthorizationRequestAndRequireSecurityHeaders(ctx context.Context, t *testing.T, downstreamAuthorizeURL string, httpClient *http.Client) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright 2022 the Pinniped contributors. All Rights Reserved.
|
||||
// Copyright 2022-2023 the Pinniped contributors. All Rights Reserved.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
package integration
|
||||
|
||||
@@ -355,7 +355,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) {
|
||||
}
|
||||
|
||||
// Start a fresh browser driver because we don't want to share cookies between the various tests in this file.
|
||||
page := browsertest.Open(t)
|
||||
browser := browsertest.OpenBrowser(t)
|
||||
|
||||
expectedUsername := env.SupervisorUpstreamOIDC.Username
|
||||
|
||||
@@ -436,17 +436,17 @@ func TestSupervisorWarnings_Browser(t *testing.T) {
|
||||
require.NotEmptyf(t, loginURL, "didn't find login URL in output: %s", output)
|
||||
|
||||
t.Logf("navigating to login page")
|
||||
require.NoError(t, page.Navigate(loginURL))
|
||||
browser.Navigate(t, loginURL)
|
||||
|
||||
// Expect to be redirected to the upstream provider and log in.
|
||||
browsertest.LoginToUpstreamOIDC(t, page, env.SupervisorUpstreamOIDC)
|
||||
browsertest.LoginToUpstreamOIDC(t, browser, env.SupervisorUpstreamOIDC)
|
||||
|
||||
// Expect to be redirected to the downstream callback which is serving the form_post HTML.
|
||||
t.Logf("waiting for response page %s", downstream.Spec.Issuer)
|
||||
browsertest.WaitForURL(t, page, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
browser.WaitForURL(t, regexp.MustCompile(regexp.QuoteMeta(downstream.Spec.Issuer)))
|
||||
|
||||
// The response page should have failed to automatically post, and should now be showing the manual instructions.
|
||||
authCode := formpostExpectManualState(t, page)
|
||||
authCode := formpostExpectManualState(t, browser)
|
||||
|
||||
// Enter the auth code in the waiting prompt, followed by a newline.
|
||||
t.Logf("'manually' pasting authorization code %q to waiting prompt", authCode)
|
||||
|
||||
@@ -1,68 +1,265 @@
|
||||
// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved.
|
||||
// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package browsertest provides integration test helpers for our browser-based tests.
|
||||
package browsertest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sclevine/agouti"
|
||||
chromedpbrowser "github.com/chromedp/cdproto/browser"
|
||||
chromedpruntime "github.com/chromedp/cdproto/runtime"
|
||||
"github.com/chromedp/chromedp"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"go.pinniped.dev/test/testlib"
|
||||
)
|
||||
|
||||
const (
|
||||
operationTimeout = 10 * time.Second
|
||||
operationPollingInterval = 100 * time.Millisecond
|
||||
)
|
||||
// Browser abstracts the specific browser driver library that we use and provides an interface
|
||||
// for integration tests to interact with the browser.
|
||||
type Browser struct {
|
||||
chromeCtx context.Context
|
||||
consoleEvents []consoleEvent
|
||||
exceptionEvents []string
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// Open a webdriver-driven browser and returns an *agouti.Page to control it. The browser will be automatically
|
||||
// closed at the end of the current test. It is configured for test purposes with the correct HTTP proxy and
|
||||
// in a mode that ignore certificate errors.
|
||||
func Open(t *testing.T) *agouti.Page {
|
||||
// consoleEvent tracks calls to the browser's console functions, like console.log().
|
||||
type consoleEvent struct {
|
||||
api string
|
||||
args []string
|
||||
}
|
||||
|
||||
// OpenBrowser opens a web browser as a subprocess and returns a Browser which allows
|
||||
// further interactions with the browser. The subprocess will be cleaned up at the end
|
||||
// of the test. Each call to OpenBrowser creates a new browser which does not share any
|
||||
// cookies with other browsers from other calls.
|
||||
func OpenBrowser(t *testing.T) *Browser {
|
||||
t.Helper()
|
||||
|
||||
// make it trivial to run all browser based tests via:
|
||||
// Make it trivial to run all browser based tests via:
|
||||
// go test -v -race -count 1 -timeout 0 ./test/integration -run '/_Browser'
|
||||
require.Contains(t, rootTestName(t), "_Browser", "browser based tests must contain the string _Browser in their name")
|
||||
|
||||
t.Logf("opening browser driver")
|
||||
env := testlib.IntegrationEnv(t)
|
||||
caps := agouti.NewCapabilities()
|
||||
|
||||
// Capture console.log(), not just console.error().
|
||||
caps["loggingPrefs"] = map[string]string{"browser": "INFO"}
|
||||
// Configure the browser.
|
||||
options := append(
|
||||
// Start with the defaults.
|
||||
chromedp.DefaultExecAllocatorOptions[:],
|
||||
// Add "ignore-certificate-errors" Chrome flag.
|
||||
chromedp.IgnoreCertErrors,
|
||||
// Uncomment this to watch the browser while the test runs.
|
||||
// chromedp.Flag("headless", false), chromedp.Flag("hide-scrollbars", false), chromedp.Flag("mute-audio", false),
|
||||
)
|
||||
|
||||
if runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
|
||||
// When running on linux, assume that we are running inside a container for CI.
|
||||
// Need to pass an extra flag in this case to avoid getting an error while launching Chrome.
|
||||
options = append(options, chromedp.NoSandbox)
|
||||
}
|
||||
|
||||
// Add the proxy flag when needed.
|
||||
if env.Proxy != "" {
|
||||
t.Logf("configuring Chrome to use proxy %q", env.Proxy)
|
||||
caps = caps.Proxy(agouti.ProxyConfig{
|
||||
ProxyType: "manual",
|
||||
HTTPProxy: env.Proxy,
|
||||
SSLProxy: env.Proxy,
|
||||
NoProxy: "127.0.0.1",
|
||||
})
|
||||
options = append(options, chromedp.ProxyServer(env.Proxy))
|
||||
}
|
||||
agoutiDriver := agouti.ChromeDriver(
|
||||
agouti.Desired(caps),
|
||||
agouti.ChromeOptions("args", []string{
|
||||
"--no-sandbox",
|
||||
"--ignore-certificate-errors",
|
||||
"--headless", // Comment out this line to see the tests happen in a visible browser window.
|
||||
}),
|
||||
// Uncomment this to see stdout/stderr from chromedriver.
|
||||
// agouti.Debug,
|
||||
|
||||
// Build the context using the above options.
|
||||
configCtx, configCancelFunc := chromedp.NewExecAllocator(context.Background(), options...)
|
||||
t.Cleanup(configCancelFunc)
|
||||
|
||||
// Create a browser context.
|
||||
chromeCtx, chromeCancelFunc := chromedp.NewContext(configCtx,
|
||||
// Uncomment to show Chrome debug logging.
|
||||
// This can be an overwhelming amount of text, but can help to debug things.
|
||||
// chromedp.WithDebugf(log.Printf),
|
||||
chromedp.WithLogf(log.Printf),
|
||||
chromedp.WithErrorf(log.Printf),
|
||||
)
|
||||
require.NoError(t, agoutiDriver.Start())
|
||||
t.Cleanup(func() { require.NoError(t, agoutiDriver.Stop()) })
|
||||
page, err := agoutiDriver.NewPage(agouti.Browser("chrome"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, page.Reset())
|
||||
return page
|
||||
t.Cleanup(chromeCancelFunc)
|
||||
|
||||
// Create the return value.
|
||||
b := &Browser{chromeCtx: chromeCtx}
|
||||
|
||||
// Subscribe to console events and exceptions to make them available later.
|
||||
chromedp.ListenTarget(chromeCtx, func(ev interface{}) {
|
||||
switch ev := ev.(type) {
|
||||
case *chromedpruntime.EventConsoleAPICalled:
|
||||
args := make([]string, len(ev.Args))
|
||||
for i, arg := range ev.Args {
|
||||
// Could also pay attention to arg.Type here, but choosing to keep it simple for now.
|
||||
args[i] = fmt.Sprintf("%s", arg.Value) //nolint:gosimple // this is an acceptable way to get a string
|
||||
}
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
b.consoleEvents = append(b.consoleEvents, consoleEvent{
|
||||
api: ev.Type.String(),
|
||||
args: args,
|
||||
})
|
||||
case *chromedpruntime.EventExceptionThrown:
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
b.exceptionEvents = append(b.exceptionEvents, ev.ExceptionDetails.Error())
|
||||
}
|
||||
})
|
||||
|
||||
// Start the web browser subprocess. Do not use a timeout here or else the browser will close after that timeout.
|
||||
// The subprocess will be cleaned up at the end of the test when the browser context is cancelled.
|
||||
require.NoError(t, chromedp.Run(chromeCtx))
|
||||
|
||||
// Grant permission to write to the clipboard because the Pinniped formpost UI has a button to copy the
|
||||
// authcode to the clipboard, and we want to be able to use that button in tests.
|
||||
require.NoError(t, chromedp.Run(chromeCtx,
|
||||
chromedpbrowser.GrantPermissions(
|
||||
[]chromedpbrowser.PermissionType{chromedpbrowser.PermissionTypeClipboardSanitizedWrite},
|
||||
),
|
||||
))
|
||||
|
||||
// To aid in debugging test failures, print the events received from the browser at the end of the test.
|
||||
t.Cleanup(func() {
|
||||
b.lock.RLock()
|
||||
defer b.lock.RUnlock()
|
||||
|
||||
consoleEventCount := len(b.consoleEvents)
|
||||
exceptionEventCount := len(b.exceptionEvents)
|
||||
|
||||
if consoleEventCount > 0 {
|
||||
t.Logf("Printing %d browser console events at end of test...", consoleEventCount)
|
||||
}
|
||||
for _, e := range b.consoleEvents {
|
||||
args := make([]string, len(e.args))
|
||||
for i, arg := range e.args {
|
||||
args[i] = fmt.Sprintf("%q", testlib.MaskTokens(arg))
|
||||
}
|
||||
t.Logf("console.%s with args: [%s]", e.api, strings.Join(args, ", "))
|
||||
}
|
||||
|
||||
if exceptionEventCount > 0 {
|
||||
t.Logf("Printing %d browser exception events at end of test...", exceptionEventCount)
|
||||
}
|
||||
for _, e := range b.exceptionEvents {
|
||||
t.Logf("exception: %s", e)
|
||||
}
|
||||
})
|
||||
|
||||
// Done. The browser is ready to be driven by the test.
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *Browser) timeout() time.Duration {
|
||||
return 30 * time.Second
|
||||
}
|
||||
|
||||
func (b *Browser) runWithTimeout(t *testing.T, timeout time.Duration, actions ...chromedp.Action) {
|
||||
t.Helper()
|
||||
timeoutCtx, cancel := context.WithTimeout(b.chromeCtx, timeout)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
err := chromedp.Run(timeoutCtx, actions...)
|
||||
if err != nil && err == context.Canceled || err == context.DeadlineExceeded {
|
||||
require.NoError(t, err, "the browser operation took longer than the allowed timeout")
|
||||
}
|
||||
require.NoError(t, err, "the browser operation failed")
|
||||
}
|
||||
|
||||
func (b *Browser) Navigate(t *testing.T, url string) {
|
||||
t.Helper()
|
||||
b.runWithTimeout(t, b.timeout(), chromedp.Navigate(url))
|
||||
}
|
||||
|
||||
func (b *Browser) Title(t *testing.T) string {
|
||||
t.Helper()
|
||||
var title string
|
||||
b.runWithTimeout(t, b.timeout(), chromedp.Title(&title))
|
||||
return title
|
||||
}
|
||||
|
||||
func (b *Browser) WaitForVisibleElements(t *testing.T, selectors ...string) {
|
||||
t.Helper()
|
||||
for _, s := range selectors {
|
||||
b.runWithTimeout(t, b.timeout(), chromedp.WaitVisible(s))
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Browser) TextOfFirstMatch(t *testing.T, selector string) string {
|
||||
t.Helper()
|
||||
var text string
|
||||
b.runWithTimeout(t, b.timeout(), chromedp.Text(selector, &text, chromedp.NodeVisible))
|
||||
return text
|
||||
}
|
||||
|
||||
func (b *Browser) AttrValueOfFirstMatch(t *testing.T, selector string, attributeName string) string {
|
||||
t.Helper()
|
||||
var value string
|
||||
var ok bool
|
||||
b.runWithTimeout(t, b.timeout(), chromedp.AttributeValue(selector, attributeName, &value, &ok))
|
||||
require.Truef(t, ok, "did not find attribute named %q on first element returned by selector %q", attributeName, selector)
|
||||
return value
|
||||
}
|
||||
|
||||
func (b *Browser) SendKeysToFirstMatch(t *testing.T, selector string, runesToType string) {
|
||||
t.Helper()
|
||||
b.runWithTimeout(t, b.timeout(), chromedp.SendKeys(selector, runesToType, chromedp.NodeVisible))
|
||||
}
|
||||
|
||||
func (b *Browser) ClickFirstMatch(t *testing.T, selector string) string {
|
||||
t.Helper()
|
||||
var text string
|
||||
b.runWithTimeout(t, b.timeout(), chromedp.Click(selector, chromedp.NodeVisible))
|
||||
return text
|
||||
}
|
||||
|
||||
// WaitForURL expects the page to eventually navigate to a URL matching the specified pattern. It waits for this
|
||||
// to occur and times out, failing the test, if it never does.
|
||||
func (b *Browser) WaitForURL(t *testing.T, regex *regexp.Regexp) {
|
||||
var lastURL string
|
||||
testlib.RequireEventuallyf(t,
|
||||
func(requireEventually *require.Assertions) {
|
||||
var url string
|
||||
requireEventually.NoError(chromedp.Run(b.chromeCtx, chromedp.Location(&url)))
|
||||
if url != lastURL {
|
||||
t.Logf("saw URL %s", testlib.MaskTokens(url))
|
||||
lastURL = url
|
||||
}
|
||||
requireEventually.Regexp(regex, url)
|
||||
},
|
||||
30*time.Second,
|
||||
100*time.Millisecond,
|
||||
"expected to browse to %s, but never got there",
|
||||
regex,
|
||||
)
|
||||
}
|
||||
|
||||
// FindConsoleEventWithTextMatching searches the browser's console that have been observed so far
|
||||
// to find an event with an argument (converted to a string) that matches the provided regexp.
|
||||
// consoleEventAPIType could be any of the console.funcName() names, e.g. "log", "info", "error", etc.
|
||||
// It returns the first matching event argument value. It doesn't worry about optimizing the search
|
||||
// speed because there should not be too many console events and because this just is a test helper.
|
||||
func (b *Browser) FindConsoleEventWithTextMatching(consoleEventAPIType string, re *regexp.Regexp) (string, bool) {
|
||||
b.lock.RLock()
|
||||
defer b.lock.RUnlock()
|
||||
|
||||
for _, e := range b.consoleEvents {
|
||||
if e.api == consoleEventAPIType {
|
||||
for _, arg := range e.args {
|
||||
if re.Match([]byte(arg)) {
|
||||
return arg, true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "", false
|
||||
}
|
||||
|
||||
func rootTestName(t *testing.T) string {
|
||||
@@ -84,50 +281,9 @@ func rootTestName(t *testing.T) string {
|
||||
}
|
||||
}
|
||||
|
||||
// WaitForVisibleElements expects the page to contain all the the elements specified by the selectors. It waits for this
|
||||
// to occur and times out, failing the test, if they never appear.
|
||||
func WaitForVisibleElements(t *testing.T, page *agouti.Page, selectors ...string) {
|
||||
t.Helper()
|
||||
|
||||
testlib.RequireEventuallyf(t,
|
||||
func(requireEventually *require.Assertions) {
|
||||
for _, sel := range selectors {
|
||||
vis, err := page.First(sel).Visible()
|
||||
requireEventually.NoError(err)
|
||||
requireEventually.Truef(vis, "expected element %q to be visible", sel)
|
||||
}
|
||||
},
|
||||
operationTimeout,
|
||||
operationPollingInterval,
|
||||
"expected to have a page with selectors %v, but it never loaded",
|
||||
selectors,
|
||||
)
|
||||
}
|
||||
|
||||
// WaitForURL expects the page to eventually navigate to a URL matching the specified pattern. It waits for this
|
||||
// to occur and times out, failing the test, if it never does.
|
||||
func WaitForURL(t *testing.T, page *agouti.Page, pat *regexp.Regexp) {
|
||||
var lastURL string
|
||||
testlib.RequireEventuallyf(t,
|
||||
func(requireEventually *require.Assertions) {
|
||||
url, err := page.URL()
|
||||
if url != lastURL {
|
||||
t.Logf("saw URL %s", testlib.MaskTokens(url))
|
||||
lastURL = url
|
||||
}
|
||||
requireEventually.NoError(err)
|
||||
requireEventually.Regexp(pat, url)
|
||||
},
|
||||
operationTimeout,
|
||||
operationPollingInterval,
|
||||
"expected to browse to %s, but never got there",
|
||||
pat,
|
||||
)
|
||||
}
|
||||
|
||||
// LoginToUpstreamOIDC expects the page to be redirected to one of several known upstream IDPs.
|
||||
// It knows how to enter the test username/password and submit the upstream login form.
|
||||
func LoginToUpstreamOIDC(t *testing.T, page *agouti.Page, upstream testlib.TestOIDCUpstream) {
|
||||
func LoginToUpstreamOIDC(t *testing.T, b *Browser, upstream testlib.TestOIDCUpstream) {
|
||||
t.Helper()
|
||||
|
||||
type config struct {
|
||||
@@ -171,21 +327,21 @@ func LoginToUpstreamOIDC(t *testing.T, page *agouti.Page, upstream testlib.TestO
|
||||
|
||||
// Expect to be redirected to the login page.
|
||||
t.Logf("waiting for redirect to %s login page", cfg.Name)
|
||||
WaitForURL(t, page, cfg.LoginPagePattern)
|
||||
b.WaitForURL(t, cfg.LoginPagePattern)
|
||||
|
||||
// Wait for the login page to be rendered.
|
||||
WaitForVisibleElements(t, page, cfg.UsernameSelector, cfg.PasswordSelector, cfg.LoginButtonSelector)
|
||||
b.WaitForVisibleElements(t, cfg.UsernameSelector, cfg.PasswordSelector, cfg.LoginButtonSelector)
|
||||
|
||||
// Fill in the username and password and click "submit".
|
||||
t.Logf("logging into %s", cfg.Name)
|
||||
require.NoError(t, page.First(cfg.UsernameSelector).Fill(upstream.Username))
|
||||
require.NoError(t, page.First(cfg.PasswordSelector).Fill(upstream.Password))
|
||||
require.NoError(t, page.First(cfg.LoginButtonSelector).Click())
|
||||
b.SendKeysToFirstMatch(t, cfg.UsernameSelector, upstream.Username)
|
||||
b.SendKeysToFirstMatch(t, cfg.PasswordSelector, upstream.Password)
|
||||
b.ClickFirstMatch(t, cfg.LoginButtonSelector)
|
||||
}
|
||||
|
||||
// LoginToUpstreamLDAP expects the page to be redirected to the Supervisor's login UI for an LDAP/AD IDP.
|
||||
// It knows how to enter the test username/password and submit the upstream login form.
|
||||
func LoginToUpstreamLDAP(t *testing.T, page *agouti.Page, issuer, username, password string) {
|
||||
func LoginToUpstreamLDAP(t *testing.T, b *Browser, issuer, username, password string) {
|
||||
t.Helper()
|
||||
|
||||
loginURLRegexp, err := regexp.Compile(`\A` + regexp.QuoteMeta(issuer+"/login") + `\?state=.+\z`)
|
||||
@@ -193,34 +349,34 @@ func LoginToUpstreamLDAP(t *testing.T, page *agouti.Page, issuer, username, pass
|
||||
|
||||
// Expect to be redirected to the login page.
|
||||
t.Logf("waiting for redirect to %s/login page", issuer)
|
||||
WaitForURL(t, page, loginURLRegexp)
|
||||
b.WaitForURL(t, loginURLRegexp)
|
||||
|
||||
// Wait for the login page to be rendered.
|
||||
WaitForVisibleElements(t, page, "#username", "#password", "#submit")
|
||||
b.WaitForVisibleElements(t, "#username", "#password", "#submit")
|
||||
|
||||
// Fill in the username and password and click "submit".
|
||||
SubmitUpstreamLDAPLoginForm(t, page, username, password)
|
||||
SubmitUpstreamLDAPLoginForm(t, b, username, password)
|
||||
}
|
||||
|
||||
func SubmitUpstreamLDAPLoginForm(t *testing.T, page *agouti.Page, username string, password string) {
|
||||
func SubmitUpstreamLDAPLoginForm(t *testing.T, b *Browser, username string, password string) {
|
||||
t.Helper()
|
||||
|
||||
// Fill in the username and password and click "submit".
|
||||
t.Logf("logging in via Supervisor's upstream LDAP/AD login UI page")
|
||||
require.NoError(t, page.First("#username").Fill(username))
|
||||
require.NoError(t, page.First("#password").Fill(password))
|
||||
require.NoError(t, page.First("#submit").Click())
|
||||
b.SendKeysToFirstMatch(t, "#username", username)
|
||||
b.SendKeysToFirstMatch(t, "#password", password)
|
||||
b.ClickFirstMatch(t, "#submit")
|
||||
}
|
||||
|
||||
func WaitForUpstreamLDAPLoginPageWithError(t *testing.T, page *agouti.Page, issuer string) {
|
||||
func WaitForUpstreamLDAPLoginPageWithError(t *testing.T, b *Browser, issuer string) {
|
||||
t.Helper()
|
||||
|
||||
// Wait for redirect back to the login page again with an error.
|
||||
t.Logf("waiting for redirect to back to login page with error message")
|
||||
loginURLRegexp, err := regexp.Compile(`\A` + regexp.QuoteMeta(issuer+"/login") + `\?err=login_error&state=.+\z`)
|
||||
require.NoError(t, err)
|
||||
WaitForURL(t, page, loginURLRegexp)
|
||||
b.WaitForURL(t, loginURLRegexp)
|
||||
|
||||
// Wait for the login page to be rendered again, this time also with an error message.
|
||||
WaitForVisibleElements(t, page, "#username", "#password", "#submit", "#alert")
|
||||
b.WaitForVisibleElements(t, "#username", "#password", "#submit", "#alert")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user