2022-02-07 19:57:54 +00:00
|
|
|
// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved.
|
2020-09-16 14:19:51 +00:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
2020-09-15 15:00:38 +00:00
|
|
|
package integration
|
|
|
|
|
|
|
|
import (
|
2020-10-13 15:41:53 +00:00
|
|
|
"bufio"
|
2020-10-14 17:28:08 +00:00
|
|
|
"bytes"
|
2020-09-15 15:00:38 +00:00
|
|
|
"context"
|
2020-10-13 15:41:53 +00:00
|
|
|
"encoding/json"
|
2020-10-14 17:28:08 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2020-10-13 15:41:53 +00:00
|
|
|
"io"
|
2020-09-15 15:00:38 +00:00
|
|
|
"io/ioutil"
|
2020-11-19 21:05:31 +00:00
|
|
|
"net/url"
|
2020-09-15 15:00:38 +00:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"path/filepath"
|
2020-10-13 15:41:53 +00:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
2020-09-15 15:00:38 +00:00
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2021-03-11 21:47:39 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
2020-09-15 15:00:38 +00:00
|
|
|
"github.com/stretchr/testify/require"
|
2020-10-14 17:28:08 +00:00
|
|
|
"golang.org/x/sync/errgroup"
|
2020-10-13 15:41:53 +00:00
|
|
|
"gopkg.in/square/go-jose.v2"
|
2021-03-04 19:46:18 +00:00
|
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
|
|
"k8s.io/apimachinery/pkg/runtime/serializer"
|
2020-10-13 15:41:53 +00:00
|
|
|
clientauthenticationv1beta1 "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1"
|
2020-09-15 15:00:38 +00:00
|
|
|
|
2021-03-04 19:46:18 +00:00
|
|
|
identityv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/identity/v1alpha1"
|
2021-03-18 14:40:59 +00:00
|
|
|
conciergescheme "go.pinniped.dev/internal/concierge/scheme"
|
2020-11-24 19:38:28 +00:00
|
|
|
"go.pinniped.dev/internal/testutil"
|
2020-11-17 18:46:54 +00:00
|
|
|
"go.pinniped.dev/pkg/oidcclient"
|
|
|
|
"go.pinniped.dev/pkg/oidcclient/filesession"
|
2021-06-22 15:23:19 +00:00
|
|
|
"go.pinniped.dev/test/testlib"
|
|
|
|
"go.pinniped.dev/test/testlib/browsertest"
|
2020-09-15 15:00:38 +00:00
|
|
|
)
|
|
|
|
|
2021-08-25 19:34:33 +00:00
|
|
|
// safe to run in parallel with serial tests since it only interacts with a test local webhook, see main_test.go.
|
|
|
|
func TestCLIGetKubeconfigStaticToken_Parallel(t *testing.T) {
|
2021-06-22 15:23:19 +00:00
|
|
|
env := testlib.IntegrationEnv(t).WithCapability(testlib.ClusterSigningKeyIsAvailable)
|
2020-09-15 15:00:38 +00:00
|
|
|
|
2020-09-22 00:55:04 +00:00
|
|
|
// Create a test webhook configuration to use with the CLI.
|
2021-03-05 01:25:43 +00:00
|
|
|
ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Minute)
|
2020-09-22 00:55:04 +00:00
|
|
|
defer cancelFunc()
|
|
|
|
|
2021-06-22 15:23:19 +00:00
|
|
|
authenticator := testlib.CreateTestWebhookAuthenticator(ctx, t)
|
2020-09-22 00:55:04 +00:00
|
|
|
|
2020-09-15 15:00:38 +00:00
|
|
|
// Build pinniped CLI.
|
2021-06-22 15:23:19 +00:00
|
|
|
pinnipedExe := testlib.PinnipedCLIPath(t)
|
2020-09-15 15:00:38 +00:00
|
|
|
|
2021-04-08 23:14:21 +00:00
|
|
|
credCacheDir := testutil.TempDir(t)
|
2021-03-23 15:26:04 +00:00
|
|
|
stdout, stderr := runPinnipedCLI(t, nil, pinnipedExe, "get", "kubeconfig",
|
|
|
|
"--static-token", env.TestUser.Token,
|
|
|
|
"--concierge-api-group-suffix", env.APIGroupSuffix,
|
|
|
|
"--concierge-authenticator-type", "webhook",
|
|
|
|
"--concierge-authenticator-name", authenticator.Name,
|
2021-04-08 23:14:21 +00:00
|
|
|
"--credential-cache", credCacheDir+"/credentials.yaml",
|
2021-03-23 15:26:04 +00:00
|
|
|
)
|
|
|
|
assert.Contains(t, stderr, "discovered CredentialIssuer")
|
|
|
|
assert.Contains(t, stderr, "discovered Concierge endpoint")
|
|
|
|
assert.Contains(t, stderr, "discovered Concierge certificate authority bundle")
|
|
|
|
assert.Contains(t, stderr, "validated connection to the cluster")
|
2020-12-15 00:42:02 +00:00
|
|
|
|
2021-03-23 15:26:04 +00:00
|
|
|
// Even the deprecated command should now generate a kubeconfig with the new "pinniped login static" command.
|
2021-06-22 15:23:19 +00:00
|
|
|
restConfig := testlib.NewRestConfigFromKubeconfig(t, stdout)
|
2021-03-23 15:26:04 +00:00
|
|
|
require.NotNil(t, restConfig.ExecProvider)
|
|
|
|
require.Equal(t, []string{"login", "static"}, restConfig.ExecProvider.Args[:2])
|
2020-12-15 00:42:02 +00:00
|
|
|
|
2021-03-23 15:26:04 +00:00
|
|
|
// In addition to the client-go based testing below, also try the kubeconfig
|
|
|
|
// with kubectl to validate that it works.
|
|
|
|
t.Run(
|
|
|
|
"access as user with kubectl",
|
2021-06-22 15:23:19 +00:00
|
|
|
testlib.AccessAsUserWithKubectlTest(stdout, env.TestUser.ExpectedUsername, env.ConciergeNamespace),
|
2021-03-23 15:26:04 +00:00
|
|
|
)
|
|
|
|
for _, group := range env.TestUser.ExpectedGroups {
|
|
|
|
group := group
|
|
|
|
t.Run(
|
|
|
|
"access as group "+group+" with kubectl",
|
2021-06-22 15:23:19 +00:00
|
|
|
testlib.AccessAsGroupWithKubectlTest(stdout, group, env.ConciergeNamespace),
|
2021-03-23 15:26:04 +00:00
|
|
|
)
|
|
|
|
}
|
2020-12-15 00:42:02 +00:00
|
|
|
|
2021-03-23 15:26:04 +00:00
|
|
|
// Create Kubernetes client with kubeconfig from pinniped CLI.
|
2021-06-22 15:23:19 +00:00
|
|
|
kubeClient := testlib.NewClientsetForKubeConfig(t, stdout)
|
2021-03-04 19:46:18 +00:00
|
|
|
|
2021-03-23 15:26:04 +00:00
|
|
|
// Validate that we can auth to the API via our user.
|
2021-06-22 15:23:19 +00:00
|
|
|
t.Run("access as user with client-go", testlib.AccessAsUserTest(ctx, env.TestUser.ExpectedUsername, kubeClient))
|
2021-03-23 15:26:04 +00:00
|
|
|
for _, group := range env.TestUser.ExpectedGroups {
|
|
|
|
group := group
|
2021-06-22 15:23:19 +00:00
|
|
|
t.Run("access as group "+group+" with client-go", testlib.AccessAsGroupTest(ctx, group, kubeClient))
|
2020-09-21 18:40:11 +00:00
|
|
|
}
|
2021-03-23 15:26:04 +00:00
|
|
|
|
|
|
|
t.Run("whoami", func(t *testing.T) {
|
|
|
|
// Validate that `pinniped whoami` returns the correct identity.
|
|
|
|
kubeconfigPath := filepath.Join(testutil.TempDir(t), "whoami-kubeconfig")
|
|
|
|
require.NoError(t, ioutil.WriteFile(kubeconfigPath, []byte(stdout), 0600))
|
|
|
|
assertWhoami(
|
|
|
|
ctx,
|
|
|
|
t,
|
|
|
|
false,
|
|
|
|
pinnipedExe,
|
|
|
|
kubeconfigPath,
|
|
|
|
env.TestUser.ExpectedUsername,
|
|
|
|
append(env.TestUser.ExpectedGroups, "system:authenticated"),
|
|
|
|
)
|
|
|
|
})
|
2020-09-15 15:00:38 +00:00
|
|
|
}
|
|
|
|
|
2021-03-06 00:14:45 +00:00
|
|
|
func runPinnipedCLI(t *testing.T, envVars []string, pinnipedExe string, args ...string) (string, string) {
|
2020-09-15 15:00:38 +00:00
|
|
|
t.Helper()
|
2021-03-23 17:07:34 +00:00
|
|
|
start := time.Now()
|
2020-12-15 00:42:02 +00:00
|
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
cmd := exec.Command(pinnipedExe, args...)
|
|
|
|
cmd.Stdout = &stdout
|
|
|
|
cmd.Stderr = &stderr
|
2021-03-06 00:14:45 +00:00
|
|
|
cmd.Env = envVars
|
2020-12-15 00:42:02 +00:00
|
|
|
require.NoErrorf(t, cmd.Run(), "stderr:\n%s\n\nstdout:\n%s\n\n", stderr.String(), stdout.String())
|
2021-06-22 15:23:19 +00:00
|
|
|
t.Logf("ran %q in %s", testlib.MaskTokens("pinniped "+strings.Join(args, " ")), time.Since(start).Round(time.Millisecond))
|
2020-12-15 00:42:02 +00:00
|
|
|
return stdout.String(), stderr.String()
|
2020-09-15 15:00:38 +00:00
|
|
|
}
|
2020-10-13 15:41:53 +00:00
|
|
|
|
2021-03-04 19:46:18 +00:00
|
|
|
func assertWhoami(ctx context.Context, t *testing.T, useProxy bool, pinnipedExe, kubeconfigPath, wantUsername string, wantGroups []string) {
|
|
|
|
t.Helper()
|
|
|
|
|
2021-06-22 15:23:19 +00:00
|
|
|
apiGroupSuffix := testlib.IntegrationEnv(t).APIGroupSuffix
|
2021-03-04 19:46:18 +00:00
|
|
|
|
|
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
cmd := exec.CommandContext(
|
|
|
|
ctx,
|
|
|
|
pinnipedExe,
|
|
|
|
"whoami",
|
|
|
|
"--kubeconfig",
|
|
|
|
kubeconfigPath,
|
|
|
|
"--output",
|
|
|
|
"yaml",
|
|
|
|
"--api-group-suffix",
|
|
|
|
apiGroupSuffix,
|
|
|
|
)
|
|
|
|
if useProxy {
|
2021-06-22 15:23:19 +00:00
|
|
|
cmd.Env = append(os.Environ(), testlib.IntegrationEnv(t).ProxyEnv()...)
|
2021-03-04 19:46:18 +00:00
|
|
|
}
|
|
|
|
cmd.Stdout = &stdout
|
|
|
|
cmd.Stderr = &stderr
|
|
|
|
require.NoErrorf(t, cmd.Run(), "stderr:\n%s\n\nstdout:\n%s\n\n", stderr.String(), stdout.String())
|
|
|
|
|
|
|
|
whoAmI := deserializeWhoAmIRequest(t, stdout.String(), apiGroupSuffix)
|
|
|
|
require.Equal(t, wantUsername, whoAmI.Status.KubernetesUserInfo.User.Username)
|
|
|
|
require.ElementsMatch(t, wantGroups, whoAmI.Status.KubernetesUserInfo.User.Groups)
|
|
|
|
}
|
|
|
|
|
|
|
|
func deserializeWhoAmIRequest(t *testing.T, data string, apiGroupSuffix string) *identityv1alpha1.WhoAmIRequest {
|
|
|
|
t.Helper()
|
|
|
|
|
2021-03-18 14:40:59 +00:00
|
|
|
scheme, _, _ := conciergescheme.New(apiGroupSuffix)
|
2021-03-04 19:46:18 +00:00
|
|
|
codecs := serializer.NewCodecFactory(scheme)
|
|
|
|
respInfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), runtime.ContentTypeYAML)
|
|
|
|
require.True(t, ok)
|
|
|
|
|
|
|
|
obj, err := runtime.Decode(respInfo.Serializer, []byte(data))
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
return obj.(*identityv1alpha1.WhoAmIRequest)
|
|
|
|
}
|
|
|
|
|
2020-10-13 15:41:53 +00:00
|
|
|
func TestCLILoginOIDC(t *testing.T) {
|
2021-06-22 15:23:19 +00:00
|
|
|
env := testlib.IntegrationEnv(t)
|
2020-10-13 15:41:53 +00:00
|
|
|
|
2020-10-22 16:49:04 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
2020-10-13 21:09:13 +00:00
|
|
|
defer cancel()
|
|
|
|
|
2020-10-13 15:41:53 +00:00
|
|
|
// Build pinniped CLI.
|
2021-06-22 15:23:19 +00:00
|
|
|
pinnipedExe := testlib.PinnipedCLIPath(t)
|
2020-10-13 15:41:53 +00:00
|
|
|
|
2020-12-08 01:39:51 +00:00
|
|
|
// Run "pinniped login oidc" to get an ExecCredential struct with an OIDC ID token.
|
2020-12-15 18:23:52 +00:00
|
|
|
credOutput, sessionCachePath := runPinnipedLoginOIDC(ctx, t, pinnipedExe)
|
2020-12-08 01:39:51 +00:00
|
|
|
|
|
|
|
// Assert some properties of the ExecCredential.
|
|
|
|
t.Logf("validating ExecCredential")
|
|
|
|
require.NotNil(t, credOutput.Status)
|
|
|
|
require.Empty(t, credOutput.Status.ClientKeyData)
|
|
|
|
require.Empty(t, credOutput.Status.ClientCertificateData)
|
|
|
|
|
|
|
|
// There should be at least 1 minute of remaining expiration (probably more).
|
|
|
|
require.NotNil(t, credOutput.Status.ExpirationTimestamp)
|
|
|
|
ttl := time.Until(credOutput.Status.ExpirationTimestamp.Time)
|
|
|
|
require.Greater(t, ttl.Milliseconds(), (1 * time.Minute).Milliseconds())
|
|
|
|
|
|
|
|
// Assert some properties about the token, which should be a valid JWT.
|
|
|
|
require.NotEmpty(t, credOutput.Status.Token)
|
|
|
|
jws, err := jose.ParseSigned(credOutput.Status.Token)
|
|
|
|
require.NoError(t, err)
|
|
|
|
claims := map[string]interface{}{}
|
|
|
|
require.NoError(t, json.Unmarshal(jws.UnsafePayloadWithoutVerification(), &claims))
|
2021-04-07 19:56:09 +00:00
|
|
|
require.Equal(t, env.CLIUpstreamOIDC.Issuer, claims["iss"])
|
|
|
|
require.Equal(t, env.CLIUpstreamOIDC.ClientID, claims["aud"])
|
|
|
|
require.Equal(t, env.CLIUpstreamOIDC.Username, claims["email"])
|
2020-12-08 01:39:51 +00:00
|
|
|
require.NotEmpty(t, claims["nonce"])
|
|
|
|
|
|
|
|
// Run the CLI again with the same session cache and login parameters.
|
|
|
|
t.Logf("starting second CLI subprocess to test session caching")
|
|
|
|
cmd2Output, err := oidcLoginCommand(ctx, t, pinnipedExe, sessionCachePath).CombinedOutput()
|
|
|
|
require.NoError(t, err, string(cmd2Output))
|
|
|
|
|
|
|
|
// Expect the CLI to output the same ExecCredential in JSON format.
|
|
|
|
t.Logf("validating second ExecCredential")
|
|
|
|
var credOutput2 clientauthenticationv1beta1.ExecCredential
|
|
|
|
require.NoErrorf(t, json.Unmarshal(cmd2Output, &credOutput2),
|
|
|
|
"command returned something other than an ExecCredential:\n%s", string(cmd2Output))
|
|
|
|
require.Equal(t, credOutput, credOutput2)
|
2021-04-07 22:54:48 +00:00
|
|
|
// the logs contain only the ExecCredential. There are 2 elements because the last one is "".
|
|
|
|
require.Len(t, strings.Split(string(cmd2Output), "\n"), 2)
|
2020-12-08 01:39:51 +00:00
|
|
|
|
|
|
|
// Overwrite the cache entry to remove the access and ID tokens.
|
|
|
|
t.Logf("overwriting cache to remove valid ID token")
|
|
|
|
cache := filesession.New(sessionCachePath)
|
|
|
|
cacheKey := oidcclient.SessionCacheKey{
|
2021-04-07 19:56:09 +00:00
|
|
|
Issuer: env.CLIUpstreamOIDC.Issuer,
|
|
|
|
ClientID: env.CLIUpstreamOIDC.ClientID,
|
2020-12-08 01:39:51 +00:00
|
|
|
Scopes: []string{"email", "offline_access", "openid", "profile"},
|
2021-04-07 19:56:09 +00:00
|
|
|
RedirectURI: strings.ReplaceAll(env.CLIUpstreamOIDC.CallbackURL, "127.0.0.1", "localhost"),
|
2020-12-08 01:39:51 +00:00
|
|
|
}
|
|
|
|
cached := cache.GetToken(cacheKey)
|
|
|
|
require.NotNil(t, cached)
|
|
|
|
require.NotNil(t, cached.RefreshToken)
|
|
|
|
require.NotEmpty(t, cached.RefreshToken.Token)
|
|
|
|
cached.IDToken = nil
|
|
|
|
cached.AccessToken = nil
|
|
|
|
cache.PutToken(cacheKey, cached)
|
|
|
|
|
|
|
|
// Run the CLI a third time with the same session cache and login parameters.
|
|
|
|
t.Logf("starting third CLI subprocess to test refresh flow")
|
|
|
|
cmd3Output, err := oidcLoginCommand(ctx, t, pinnipedExe, sessionCachePath).CombinedOutput()
|
|
|
|
require.NoError(t, err, string(cmd2Output))
|
|
|
|
|
|
|
|
// Expect the CLI to output a new ExecCredential in JSON format (different from the one returned the first two times).
|
|
|
|
t.Logf("validating third ExecCredential")
|
|
|
|
var credOutput3 clientauthenticationv1beta1.ExecCredential
|
|
|
|
require.NoErrorf(t, json.Unmarshal(cmd3Output, &credOutput3),
|
|
|
|
"command returned something other than an ExecCredential:\n%s", string(cmd2Output))
|
|
|
|
require.NotEqual(t, credOutput2.Status.Token, credOutput3.Status.Token)
|
2021-04-07 22:54:48 +00:00
|
|
|
// the logs contain only the ExecCredential. There are 2 elements because the last one is "".
|
|
|
|
require.Len(t, strings.Split(string(cmd3Output), "\n"), 2)
|
2021-04-07 22:30:29 +00:00
|
|
|
|
|
|
|
t.Logf("starting fourth CLI subprocess to test debug logging")
|
|
|
|
err = os.Setenv("PINNIPED_DEBUG", "true")
|
|
|
|
require.NoError(t, err)
|
|
|
|
command := oidcLoginCommand(ctx, t, pinnipedExe, sessionCachePath)
|
|
|
|
cmd4CombinedOutput, err := command.CombinedOutput()
|
2021-04-07 22:54:48 +00:00
|
|
|
cmd4StringOutput := string(cmd4CombinedOutput)
|
|
|
|
require.NoError(t, err, cmd4StringOutput)
|
|
|
|
|
2021-04-21 20:05:32 +00:00
|
|
|
// the logs contain only the 4 debug lines plus the ExecCredential. There are 6 elements because the last one is "".
|
|
|
|
require.Len(t, strings.Split(cmd4StringOutput, "\n"), 6)
|
2021-04-07 22:54:48 +00:00
|
|
|
require.Contains(t, cmd4StringOutput, "Performing OIDC login")
|
|
|
|
require.Contains(t, cmd4StringOutput, "Found unexpired cached token")
|
|
|
|
require.Contains(t, cmd4StringOutput, "No concierge configured, skipping token credential exchange")
|
2021-04-21 20:05:32 +00:00
|
|
|
require.Contains(t, cmd4StringOutput, "caching cluster credential for future use.")
|
2021-04-07 22:54:48 +00:00
|
|
|
require.Contains(t, cmd4StringOutput, credOutput3.Status.Token)
|
2021-04-08 17:14:29 +00:00
|
|
|
err = os.Unsetenv("PINNIPED_DEBUG")
|
|
|
|
require.NoError(t, err)
|
2020-12-08 01:39:51 +00:00
|
|
|
}
|
|
|
|
|
2020-12-15 18:23:52 +00:00
|
|
|
func runPinnipedLoginOIDC(
|
2020-12-08 01:39:51 +00:00
|
|
|
ctx context.Context,
|
|
|
|
t *testing.T,
|
|
|
|
pinnipedExe string,
|
|
|
|
) (clientauthenticationv1beta1.ExecCredential, string) {
|
|
|
|
t.Helper()
|
|
|
|
|
2021-06-22 15:23:19 +00:00
|
|
|
env := testlib.IntegrationEnv(t)
|
2020-12-08 01:39:51 +00:00
|
|
|
|
2020-10-21 20:02:42 +00:00
|
|
|
// Make a temp directory to hold the session cache for this test.
|
2020-11-24 19:38:28 +00:00
|
|
|
sessionCachePath := testutil.TempDir(t) + "/sessions.yaml"
|
2020-10-21 20:02:42 +00:00
|
|
|
|
2020-12-08 01:39:51 +00:00
|
|
|
// Start the browser driver.
|
|
|
|
page := browsertest.Open(t)
|
|
|
|
|
|
|
|
// Start the CLI running the "login oidc [...]" command with stdout/stderr connected to pipes.
|
2020-10-22 22:35:06 +00:00
|
|
|
cmd := oidcLoginCommand(ctx, t, pinnipedExe, sessionCachePath)
|
2020-10-14 17:28:08 +00:00
|
|
|
stderr, err := cmd.StderrPipe()
|
|
|
|
require.NoError(t, err)
|
|
|
|
stdout, err := cmd.StdoutPipe()
|
|
|
|
require.NoError(t, err)
|
2020-10-22 22:35:06 +00:00
|
|
|
t.Logf("starting CLI subprocess")
|
2020-10-14 17:28:08 +00:00
|
|
|
require.NoError(t, cmd.Start())
|
|
|
|
t.Cleanup(func() {
|
|
|
|
err := cmd.Wait()
|
|
|
|
t.Logf("CLI subprocess exited with code %d", cmd.ProcessState.ExitCode())
|
|
|
|
require.NoErrorf(t, err, "CLI process did not exit cleanly")
|
|
|
|
})
|
2020-10-13 15:41:53 +00:00
|
|
|
|
|
|
|
// Start a background goroutine to read stderr from the CLI and parse out the login URL.
|
2022-02-07 19:57:54 +00:00
|
|
|
loginURLChan := make(chan string, 1)
|
2020-10-14 17:28:08 +00:00
|
|
|
spawnTestGoroutine(t, func() (err error) {
|
2021-04-07 22:30:29 +00:00
|
|
|
t.Helper()
|
2020-10-14 17:28:08 +00:00
|
|
|
defer func() {
|
|
|
|
closeErr := stderr.Close()
|
|
|
|
if closeErr == nil || errors.Is(closeErr, os.ErrClosed) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err == nil {
|
|
|
|
err = fmt.Errorf("stderr stream closed with error: %w", closeErr)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2021-06-22 15:23:19 +00:00
|
|
|
reader := bufio.NewReader(testlib.NewLoggerReader(t, "stderr", stderr))
|
2021-04-07 22:30:29 +00:00
|
|
|
|
|
|
|
scanner := bufio.NewScanner(reader)
|
|
|
|
for scanner.Scan() {
|
2021-07-08 19:32:44 +00:00
|
|
|
loginURL, err := url.Parse(strings.TrimSpace(scanner.Text()))
|
|
|
|
if err == nil && loginURL.Scheme == "https" {
|
2022-02-07 19:57:54 +00:00
|
|
|
loginURLChan <- loginURL.String() // this channel is buffered so this will not block
|
2021-04-07 22:30:29 +00:00
|
|
|
return nil
|
|
|
|
}
|
2020-10-14 17:28:08 +00:00
|
|
|
}
|
2021-04-07 22:30:29 +00:00
|
|
|
|
2021-07-08 19:32:44 +00:00
|
|
|
return fmt.Errorf("expected stderr to contain login URL")
|
2020-10-14 17:28:08 +00:00
|
|
|
})
|
2020-10-13 15:41:53 +00:00
|
|
|
|
|
|
|
// Start a background goroutine to read stdout from the CLI and parse out an ExecCredential.
|
2022-02-07 19:57:54 +00:00
|
|
|
credOutputChan := make(chan clientauthenticationv1beta1.ExecCredential, 1)
|
2020-10-14 17:28:08 +00:00
|
|
|
spawnTestGoroutine(t, func() (err error) {
|
|
|
|
defer func() {
|
2020-12-15 18:24:28 +00:00
|
|
|
closeErr := stdout.Close()
|
2020-10-14 17:28:08 +00:00
|
|
|
if closeErr == nil || errors.Is(closeErr, os.ErrClosed) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err == nil {
|
|
|
|
err = fmt.Errorf("stdout stream closed with error: %w", closeErr)
|
|
|
|
}
|
|
|
|
}()
|
2021-06-22 15:23:19 +00:00
|
|
|
reader := bufio.NewReader(testlib.NewLoggerReader(t, "stdout", stdout))
|
2020-10-13 15:41:53 +00:00
|
|
|
var out clientauthenticationv1beta1.ExecCredential
|
2020-10-14 17:28:08 +00:00
|
|
|
if err := json.NewDecoder(reader).Decode(&out); err != nil {
|
|
|
|
return fmt.Errorf("could not read ExecCredential from stdout: %w", err)
|
|
|
|
}
|
2022-02-07 19:57:54 +00:00
|
|
|
credOutputChan <- out // this channel is buffered so this will not block
|
2020-10-14 17:28:08 +00:00
|
|
|
return readAndExpectEmpty(reader)
|
2020-10-13 21:09:13 +00:00
|
|
|
})
|
2020-10-13 15:41:53 +00:00
|
|
|
|
|
|
|
// Wait for the CLI to print out the login URL and open the browser to it.
|
|
|
|
t.Logf("waiting for CLI to output login URL")
|
|
|
|
var loginURL string
|
|
|
|
select {
|
|
|
|
case <-time.After(1 * time.Minute):
|
|
|
|
require.Fail(t, "timed out waiting for login URL")
|
|
|
|
case loginURL = <-loginURLChan:
|
|
|
|
}
|
|
|
|
t.Logf("navigating to login page")
|
|
|
|
require.NoError(t, page.Navigate(loginURL))
|
|
|
|
|
2020-12-02 21:29:54 +00:00
|
|
|
// Expect to be redirected to the upstream provider and log in.
|
2021-04-07 19:56:09 +00:00
|
|
|
browsertest.LoginToUpstream(t, page, env.CLIUpstreamOIDC)
|
2020-10-13 15:41:53 +00:00
|
|
|
|
2020-12-02 21:29:54 +00:00
|
|
|
// Expect to be redirected to the localhost callback.
|
|
|
|
t.Logf("waiting for redirect to callback")
|
2021-07-09 21:26:05 +00:00
|
|
|
callbackURLPattern := regexp.MustCompile(`\A` + regexp.QuoteMeta(env.CLIUpstreamOIDC.CallbackURL) + `(\?.+)?\z`)
|
2020-12-02 21:29:54 +00:00
|
|
|
browsertest.WaitForURL(t, page, callbackURLPattern)
|
2020-10-13 15:41:53 +00:00
|
|
|
|
|
|
|
// 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")
|
2020-12-02 21:29:54 +00:00
|
|
|
browsertest.WaitForVisibleElements(t, page, "pre")
|
2020-10-13 15:41:53 +00:00
|
|
|
msg, err := page.First("pre").Text()
|
|
|
|
require.NoError(t, err)
|
|
|
|
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.
|
|
|
|
t.Logf("waiting for CLI to output ExecCredential JSON")
|
|
|
|
var credOutput clientauthenticationv1beta1.ExecCredential
|
|
|
|
select {
|
|
|
|
case <-time.After(10 * time.Second):
|
|
|
|
require.Fail(t, "timed out waiting for exec credential output")
|
|
|
|
case credOutput = <-credOutputChan:
|
|
|
|
}
|
|
|
|
|
2020-12-08 01:39:51 +00:00
|
|
|
return credOutput, sessionCachePath
|
2020-10-13 15:41:53 +00:00
|
|
|
}
|
|
|
|
|
2020-10-14 17:28:08 +00:00
|
|
|
func readAndExpectEmpty(r io.Reader) (err error) {
|
|
|
|
var remainder bytes.Buffer
|
|
|
|
_, err = io.Copy(&remainder, r)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if r := remainder.String(); r != "" {
|
|
|
|
return fmt.Errorf("expected remainder to be empty, but got %q", r)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-02-07 19:57:54 +00:00
|
|
|
// Note: Callers should ensure that f eventually returns, otherwise this helper will hang forever in t.Cleanup.
|
2020-10-14 17:28:08 +00:00
|
|
|
func spawnTestGoroutine(t *testing.T, f func() error) {
|
|
|
|
t.Helper()
|
|
|
|
var eg errgroup.Group
|
|
|
|
t.Cleanup(func() {
|
|
|
|
require.NoError(t, eg.Wait(), "background goroutine failed")
|
|
|
|
})
|
|
|
|
eg.Go(f)
|
|
|
|
}
|
2020-10-22 22:35:06 +00:00
|
|
|
|
|
|
|
func oidcLoginCommand(ctx context.Context, t *testing.T, pinnipedExe string, sessionCachePath string) *exec.Cmd {
|
2021-06-22 15:23:19 +00:00
|
|
|
env := testlib.IntegrationEnv(t)
|
2021-04-07 19:56:09 +00:00
|
|
|
callbackURL, err := url.Parse(env.CLIUpstreamOIDC.CallbackURL)
|
2020-11-19 21:05:31 +00:00
|
|
|
require.NoError(t, err)
|
2020-11-16 16:40:18 +00:00
|
|
|
cmd := exec.CommandContext(ctx, pinnipedExe, "login", "oidc",
|
2021-04-07 19:56:09 +00:00
|
|
|
"--issuer", env.CLIUpstreamOIDC.Issuer,
|
|
|
|
"--client-id", env.CLIUpstreamOIDC.ClientID,
|
2020-12-04 17:21:30 +00:00
|
|
|
"--scopes", "offline_access,openid,email,profile",
|
2020-11-19 21:05:31 +00:00
|
|
|
"--listen-port", callbackURL.Port(),
|
2020-10-22 22:35:06 +00:00
|
|
|
"--session-cache", sessionCachePath,
|
2021-04-08 23:14:21 +00:00
|
|
|
"--credential-cache", testutil.TempDir(t)+"/credentials.yaml",
|
2020-10-22 22:35:06 +00:00
|
|
|
"--skip-browser",
|
|
|
|
)
|
2020-11-16 20:04:08 +00:00
|
|
|
|
|
|
|
// If there is a custom CA bundle, pass it via --ca-bundle and a temporary file.
|
2021-04-07 19:56:09 +00:00
|
|
|
if env.CLIUpstreamOIDC.CABundle != "" {
|
2020-11-24 19:38:28 +00:00
|
|
|
path := filepath.Join(testutil.TempDir(t), "test-ca.pem")
|
2021-04-07 19:56:09 +00:00
|
|
|
require.NoError(t, ioutil.WriteFile(path, []byte(env.CLIUpstreamOIDC.CABundle), 0600))
|
2020-11-16 20:04:08 +00:00
|
|
|
cmd.Args = append(cmd.Args, "--ca-bundle", path)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If there is a custom proxy, set it using standard environment variables.
|
2020-12-15 17:45:40 +00:00
|
|
|
cmd.Env = append(os.Environ(), env.ProxyEnv()...)
|
2020-11-16 16:40:18 +00:00
|
|
|
return cmd
|
2020-10-22 22:35:06 +00:00
|
|
|
}
|