feat(cli): Add support for password credential in redis helper (#6213)

This commit is contained in:
Justin Nguyen authored and Bharath Gajjala committed 2025-11-13 12:28:54 -08:00
1 parent d4f7bd55d1
commit 1ac444d0a8
11 files changed
+581 -224

No files matched your search

+40
View File
@@ -12,6 +12,7 @@ import (
const (
usernamePasswordCredentialType = "username_password"
passwordCredentialType = "password"
sshPrivateKeyCredentialType = "ssh_private_key"
)
@@ -26,6 +27,16 @@ type UsernamePassword struct {
Consumed bool
}
// Password contains a password credential
type Password struct {
Password string `mapstructure:"password"`
Raw *targets.SessionCredential
// Consumed can be set by the caller to indicate that the credential has
// been used, e.g. displayed to the user
Consumed bool
}
// SshPrivateKey contains the username and private key with optional passphrase
// for the key
type SshPrivateKey struct {
@@ -41,6 +52,7 @@ type SshPrivateKey struct {
type Credentials struct {
UsernamePassword []UsernamePassword
Password []Password
SshPrivateKey []SshPrivateKey
// Unspecified are credentials that do not match one of the types above
Unspecified []*targets.SessionCredential
@@ -62,6 +74,11 @@ func (c Credentials) UnconsumedSessionCredentials() []*targets.SessionCredential
out = append(out, c.Raw)
}
}
for _, c := range c.Password {
if !c.Consumed {
out = append(out, c.Raw)
}
}
return out
}
@@ -76,6 +93,7 @@ func ParseCredentials(creds []*targets.SessionCredential) (Credentials, error) {
}
var upCred UsernamePassword
var pCred Password
var spkCred SshPrivateKey
switch cred.CredentialSource.CredentialType {
case usernamePasswordCredentialType:
@@ -90,6 +108,18 @@ func ParseCredentials(creds []*targets.SessionCredential) (Credentials, error) {
continue
}
case passwordCredentialType:
// Decode attributes from credential struct
if err := mapstructure.Decode(cred.Credential, &pCred); err != nil {
return Credentials{}, err
}
if pCred.Password != "" {
pCred.Raw = cred
out.Password = append(out.Password, pCred)
continue
}
case sshPrivateKeyCredentialType:
// Decode attributes from credential struct
if err := mapstructure.Decode(cred.Credential, &spkCred); err != nil {
@@ -116,6 +146,16 @@ func ParseCredentials(creds []*targets.SessionCredential) (Credentials, error) {
continue
}
// Attempt unmarshaling into password creds
if err := mapstructure.Decode(cred.Secret.Decoded, &pCred); err != nil {
return Credentials{}, err
}
if pCred.Password != "" {
pCred.Raw = cred
out.Password = append(out.Password, pCred)
continue
}
// Attempt unmarshaling into ssh private key creds
if err := mapstructure.Decode(cred.Secret.Decoded, &spkCred); err != nil {
return Credentials{}, err
+154 -1
View File
@@ -29,6 +29,15 @@ var (
},
}
typedPassword = &targets.SessionCredential{
CredentialSource: &targets.CredentialSource{
CredentialType: passwordCredentialType,
},
Credential: map[string]any{
"password": "pass",
},
}
typedSshPrivateKey = &targets.SessionCredential{
CredentialSource: &targets.CredentialSource{
CredentialType: sshPrivateKeyCredentialType,
@@ -75,6 +84,17 @@ var (
},
}
vaultPassword = &targets.SessionCredential{
CredentialSource: &targets.CredentialSource{
Type: vaultGenericLibrarySubtype,
},
Secret: &targets.SessionSecret{
Decoded: map[string]any{
"password": "vault-decoded-pass",
},
},
}
vaultSshPrivateKey = &targets.SessionCredential{
CredentialSource: &targets.CredentialSource{
Type: vaultGenericLibrarySubtype,
@@ -119,6 +139,17 @@ var (
},
}
staticPassword = &targets.SessionCredential{
CredentialSource: &targets.CredentialSource{
Type: staticSubtype,
},
Secret: &targets.SessionSecret{
Decoded: map[string]any{
"password": "static-decoded-pass",
},
},
}
staticSshPrivateKey = &targets.SessionCredential{
CredentialSource: &targets.CredentialSource{
Type: staticSubtype,
@@ -215,6 +246,21 @@ func Test_parseCredentials(t *testing.T) {
},
wantErr: false,
},
{
name: "password-typed",
creds: []*targets.SessionCredential{
typedPassword,
},
wantCreds: Credentials{
Password: []Password{
{
Password: "pass",
Raw: typedPassword,
},
},
},
wantErr: false,
},
{
name: "ssh-private-key-typed",
creds: []*targets.SessionCredential{
@@ -247,6 +293,21 @@ func Test_parseCredentials(t *testing.T) {
},
wantErr: false,
},
{
name: "vault-password-decoded",
creds: []*targets.SessionCredential{
vaultPassword,
},
wantCreds: Credentials{
Password: []Password{
{
Password: "vault-decoded-pass",
Raw: vaultPassword,
},
},
},
wantErr: false,
},
{
name: "vault-private-key-decoded",
creds: []*targets.SessionCredential{
@@ -343,6 +404,21 @@ func Test_parseCredentials(t *testing.T) {
},
wantErr: false,
},
{
name: "static-password-decoded",
creds: []*targets.SessionCredential{
staticPassword,
},
wantCreds: Credentials{
Password: []Password{
{
Password: "static-decoded-pass",
Raw: staticPassword,
},
},
},
wantErr: false,
},
{
name: "static-private-key-decoded",
creds: []*targets.SessionCredential{
@@ -388,7 +464,7 @@ func Test_parseCredentials(t *testing.T) {
creds: []*targets.SessionCredential{
staticSshPrivateKey, UnspecifiedCred1, vaultSshPrivateKey, typedUsernamePassword,
UnspecifiedCred, vaultUsernamePassword, typedSshPrivateKey, staticUsernamePassword,
staticKv,
staticKv, typedPassword, vaultPassword, staticPassword,
},
wantCreds: Credentials{
SshPrivateKey: []SshPrivateKey{
@@ -425,6 +501,20 @@ func Test_parseCredentials(t *testing.T) {
Raw: typedUsernamePassword,
},
},
Password: []Password{
{
Password: "static-decoded-pass",
Raw: staticPassword,
},
{
Password: "vault-decoded-pass",
Raw: vaultPassword,
},
{
Password: "pass",
Raw: typedPassword,
},
},
Unspecified: []*targets.SessionCredential{
UnspecifiedCred, UnspecifiedCred1, staticKv,
},
@@ -447,6 +537,7 @@ func Test_parseCredentials(t *testing.T) {
assert.ElementsMatch(tt.wantCreds.UsernamePassword, creds.UsernamePassword)
assert.ElementsMatch(tt.wantCreds.SshPrivateKey, creds.SshPrivateKey)
assert.ElementsMatch(tt.wantCreds.Unspecified, creds.Unspecified)
assert.ElementsMatch(tt.wantCreds.Password, creds.Password)
})
}
}
@@ -507,6 +598,29 @@ func Test_unconsumedSessionCredentials(t *testing.T) {
},
wantCreds: nil,
},
{
name: "p",
creds: Credentials{
Password: []Password{
{
Raw: vaultPassword,
},
},
},
wantCreds: []*targets.SessionCredential{vaultPassword},
},
{
name: "p-consumed",
creds: Credentials{
Password: []Password{
{
Raw: vaultPassword,
Consumed: true,
},
},
},
wantCreds: nil,
},
{
name: "Unspecified",
creds: Credentials{
@@ -542,10 +656,23 @@ func Test_unconsumedSessionCredentials(t *testing.T) {
Consumed: true,
},
},
Password: []Password{
{
Raw: staticPassword,
},
{
Raw: vaultPassword,
},
{
Raw: typedPassword,
Consumed: true,
},
},
Unspecified: []*targets.SessionCredential{UnspecifiedCred, UnspecifiedCred1},
},
wantCreds: []*targets.SessionCredential{
vaultSshPrivateKey, typedSshPrivateKey, vaultUsernamePassword, UnspecifiedCred, UnspecifiedCred1,
staticPassword, vaultPassword,
},
},
{
@@ -579,6 +706,20 @@ func Test_unconsumedSessionCredentials(t *testing.T) {
Consumed: true,
},
},
Password: []Password{
{
Raw: staticPassword,
Consumed: true,
},
{
Raw: vaultPassword,
Consumed: true,
},
{
Raw: typedPassword,
Consumed: true,
},
},
Unspecified: []*targets.SessionCredential{UnspecifiedCred, UnspecifiedCred1},
},
wantCreds: []*targets.SessionCredential{
@@ -610,11 +751,23 @@ func Test_unconsumedSessionCredentials(t *testing.T) {
Raw: typedUsernamePassword,
},
},
Password: []Password{
{
Raw: staticPassword,
},
{
Raw: vaultPassword,
},
{
Raw: typedPassword,
},
},
Unspecified: []*targets.SessionCredential{UnspecifiedCred, UnspecifiedCred1},
},
wantCreds: []*targets.SessionCredential{
staticSshPrivateKey, UnspecifiedCred1, vaultSshPrivateKey, typedUsernamePassword,
UnspecifiedCred, vaultUsernamePassword, typedSshPrivateKey, staticUsernamePassword,
staticPassword, vaultPassword, typedPassword,
},
},
}
+13 -3
View File
@@ -49,13 +49,21 @@ func (r *redisFlags) buildArgs(c *Command, port, ip, _ string, creds proxy.Crede
var username, password string
retCreds = creds
if len(retCreds.UsernamePassword) > 0 {
switch {
case len(retCreds.UsernamePassword) > 0:
// Mark credential as consumed, such that it is not printed to the user
retCreds.UsernamePassword[0].Consumed = true
// Grab the first available username/password credential brokered
username = retCreds.UsernamePassword[0].Username
password = retCreds.UsernamePassword[0].Password
case len(retCreds.Password) > 0:
// Mark credential as consumed, such that it is not printed to the user
retCreds.Password[0].Consumed = true
// Grab the first available password credential brokered
password = retCreds.Password[0].Password
}
switch r.flagRedisStyle {
@@ -69,12 +77,14 @@ func (r *redisFlags) buildArgs(c *Command, port, ip, _ string, creds proxy.Crede
case username != "":
args = append(args, "--user", username)
case c.flagUsername != "":
args = append(args, "--user", c.flagUsername, "--askpass")
args = append(args, "--user", c.flagUsername)
}
// Password is read by redis-cli via environment variable. The password disappears after the command exits.
if password != "" {
envs = append(envs, fmt.Sprintf("REDISCLI_AUTH=%s", password))
} else {
// prompt for password if it wasn't provided
envs = append(envs, "--askpass")
}
}
@@ -262,6 +262,41 @@ func CreateStaticCredentialUsernamePasswordCli(t testing.TB, ctx context.Context
return credentialId, nil
}
// CreateStaticCredentialPasswordCli uses the cli to create a new password credential in the
// provided static credential store.
// Returns the id of the new credential
func CreateStaticCredentialPasswordCli(t testing.TB, ctx context.Context, credentialStoreId string, password string) (string, error) {
name, err := base62.Random(16)
if err != nil {
return "", err
}
output := e2e.RunCommand(ctx, "boundary",
e2e.WithArgs(
"credentials", "create", "password",
"-credential-store-id", credentialStoreId,
"-password", "env://E2E_CREDENTIALS_PASSWORD",
"-name", fmt.Sprintf("e2e Credential %s", name),
"-description", "e2e",
"-format", "json",
),
e2e.WithEnv("E2E_CREDENTIALS_PASSWORD", password),
)
if output.Err != nil {
return "", fmt.Errorf("%w: %s", output.Err, string(output.Stderr))
}
var createCredentialsResult credentials.CredentialCreateResult
err = json.Unmarshal(output.Stdout, &createCredentialsResult)
if err != nil {
return "", err
}
credentialId := createCredentialsResult.Item.Id
t.Logf("Created Password Credential: %s", credentialId)
return credentialId, nil
}
// CreateStaticCredentialUsernamePasswordDomainCli uses the cli to create a new username password domain credential in the
// provided static credential store.
// Returns the id of the new credential
-79
View File
@@ -35,12 +35,6 @@ type cassandraConfig struct {
NetworkAlias string
}
type redisConfig struct {
User string
Password string
NetworkAlias string
}
// StartBoundaryDatabase spins up a postgres database in a docker container.
// Returns information about the container
func StartBoundaryDatabase(t testing.TB, pool *dockertest.Pool, network *dockertest.Network, repository, tag string) *Container {
@@ -478,63 +472,6 @@ func StartCassandra(t testing.TB, pool *dockertest.Pool, network *dockertest.Net
}
}
// StartRedis starts a Redis database in a docker container.
// Returns information about the container
func StartRedis(t testing.TB, pool *dockertest.Pool, network *dockertest.Network, repository, tag string) *Container {
t.Log("Starting Redis database...")
c, err := LoadConfig()
require.NoError(t, err)
err = pool.Client.PullImage(docker.PullImageOptions{
Repository: fmt.Sprintf("%s/%s", c.DockerMirror, repository),
Tag: tag,
}, docker.AuthConfiguration{})
require.NoError(t, err)
config := redisConfig{
User: "e2eboundary",
Password: "e2eboundary",
NetworkAlias: "e2eredis",
}
resource, err := pool.RunWithOptions(&dockertest.RunOptions{
Repository: fmt.Sprintf("%s/%s", c.DockerMirror, repository),
Tag: tag,
ExposedPorts: []string{"6379/tcp"},
Name: config.NetworkAlias,
Networks: []*dockertest.Network{network},
})
require.NoError(t, err)
err = pool.Retry(func() error {
cmd := exec.Command("docker", "exec", config.NetworkAlias, "redis-cli", "PING")
output, cmdErr := cmd.CombinedOutput()
if cmdErr != nil {
return fmt.Errorf("failed to connect to Redis container '%s': %v\nOutput: %s", config.NetworkAlias, cmdErr, string(output))
}
return nil
})
require.NoError(t, err, "Redis container did not start in time or is not healthy")
err = setupRedisAuthAndUser(t, resource, pool, &config)
require.NoError(t, err)
return &Container{
Resource: resource,
UriLocalhost: fmt.Sprintf(
"redis://%s:%s@localhost:6379",
config.User,
config.Password,
),
UriNetwork: fmt.Sprintf(
"redis://%s:%s@%s:6379",
config.User,
config.Password,
config.NetworkAlias,
),
}
}
// setupCassandraAuthAndUser enables authentication on a Cassandra container and creates a user with permissions.
func setupCassandraAuthAndUser(t testing.TB, resource *dockertest.Resource, pool *dockertest.Pool, config *cassandraConfig) error {
t.Helper()
@@ -593,19 +530,3 @@ func setupCassandraAuthAndUser(t testing.TB, resource *dockertest.Resource, pool
}
return nil
}
// setupRedisAuthAndUser configures a Redis container by creating a user with permissions.
func setupRedisAuthAndUser(t testing.TB, resource *dockertest.Resource, pool *dockertest.Pool, config *redisConfig) error {
t.Helper()
t.Log("Configuring Redis authentication and user permissions...")
err := exec.Command(
"docker", "exec", config.NetworkAlias, "redis-cli",
"ACL", "SETUSER", config.User, "on", fmt.Sprintf(">%s", config.Password), "+@read", "+@write", "allkeys",
).Run()
if err != nil {
return err
}
return nil
}
+146
View File
@@ -0,0 +1,146 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package infra
import (
"fmt"
"io"
"net/url"
"os/exec"
"strings"
"testing"
"github.com/ory/dockertest/v3"
"github.com/ory/dockertest/v3/docker"
"github.com/stretchr/testify/require"
)
type RedisContainerInfo struct {
Hostname string
Port string
Username string
Password string
}
type redisConfig struct {
User string
Password string
NetworkAlias string
}
// SetupRedisContainer starts a Redis container and returns its connection info
func SetupRedisContainer(t *testing.T) *RedisContainerInfo {
pool, err := dockertest.NewPool("")
require.NoError(t, err)
network, err := pool.NetworksByName("e2e_cluster")
require.NoError(t, err, "Failed to get e2e_cluster network")
c := startRedis(t, pool, &network[0], "redis", "latest")
require.NotNil(t, c, "Redis container should not be nil")
t.Cleanup(func() {
if err := pool.Purge(c.Resource); err != nil {
t.Logf("Failed to purge Redis container: %v", err)
}
})
u, err := url.Parse(c.UriNetwork)
t.Log(u)
require.NoError(t, err, "Failed to parse Redis URL")
user, hostname, port := u.User.Username(), u.Hostname(), u.Port()
pw, pwSet := u.User.Password()
t.Logf("Redis info: user=%s, host=%s, port=%s, password-set:%t",
user, hostname, port, pwSet)
return &RedisContainerInfo{
Hostname: hostname,
Port: port,
Username: user,
Password: pw,
}
}
// startRedis starts a Redis database in a docker container.
// Returns information about the container
func startRedis(t testing.TB, pool *dockertest.Pool, network *dockertest.Network, repository, tag string) *Container {
t.Log("Starting Redis database...")
c, err := LoadConfig()
require.NoError(t, err)
err = pool.Client.PullImage(docker.PullImageOptions{
Repository: fmt.Sprintf("%s/%s", c.DockerMirror, repository),
Tag: tag,
}, docker.AuthConfiguration{})
require.NoError(t, err)
config := redisConfig{
User: "e2eboundary",
Password: "e2eboundary",
NetworkAlias: "e2eredis",
}
resource, err := pool.RunWithOptions(&dockertest.RunOptions{
Repository: fmt.Sprintf("%s/%s", c.DockerMirror, repository),
Tag: tag,
ExposedPorts: []string{"6379/tcp"},
Name: config.NetworkAlias,
Networks: []*dockertest.Network{network},
})
require.NoError(t, err)
err = pool.Retry(func() error {
cmd := exec.Command("docker", "exec", config.NetworkAlias, "redis-cli", "PING")
output, cmdErr := cmd.CombinedOutput()
if cmdErr != nil {
return fmt.Errorf("failed to connect to Redis container '%s': %v\nOutput: %s", config.NetworkAlias, cmdErr, string(output))
}
return nil
})
require.NoError(t, err, "Redis container did not start in time or is not healthy")
// configure redis users
// e2e user
err = exec.Command(
"docker", "exec", config.NetworkAlias, "redis-cli",
"ACL", "SETUSER", config.User, "on", fmt.Sprintf(">%s", config.Password), "+@all", "allkeys",
).Run()
require.NoError(t, err)
// default user
err = exec.Command(
"docker", "exec", config.NetworkAlias, "redis-cli",
"ACL", "SETUSER", "default", fmt.Sprintf(">%s", config.Password),
).Run()
require.NoError(t, err)
return &Container{
Resource: resource,
UriLocalhost: fmt.Sprintf(
"redis://%s:%s@localhost:6379",
config.User,
config.Password,
),
UriNetwork: fmt.Sprintf(
"redis://%s:%s@%s:6379",
config.User,
config.Password,
config.NetworkAlias,
),
}
}
func SendRedisCommand(stdin io.WriteCloser, stdout io.ReadCloser, cmdStr string) (string, error) {
_, err := stdin.Write([]byte(cmdStr))
if err != nil {
return "", err
}
buf := make([]byte, 1024)
n, err := stdout.Read(buf)
if err != nil {
return "", err
}
return strings.TrimSpace(string(buf[:n])), nil
}
@@ -0,0 +1,96 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package base_test
import (
"context"
"io"
"os/exec"
"testing"
"github.com/hashicorp/boundary/internal/target"
"github.com/hashicorp/boundary/testing/internal/e2e"
"github.com/hashicorp/boundary/testing/internal/e2e/boundary"
"github.com/hashicorp/boundary/testing/internal/e2e/infra"
"github.com/stretchr/testify/require"
)
// TestCliTcpTargetConnectRedisPassword uses the boundary cli to connect to a target
// using `connect redis` and a password credential.
func TestCliTcpTargetConnectRedisPassword(t *testing.T) {
e2e.MaybeSkipTest(t)
// Setup
ctx := context.Background()
redisInfo := infra.SetupRedisContainer(t)
boundary.AuthenticateAdminCli(t, ctx)
// Create Boundary resources
orgId, err := boundary.CreateOrgCli(t, ctx)
require.NoError(t, err)
t.Cleanup(func() {
ctx := context.Background()
boundary.AuthenticateAdminCli(t, ctx)
output := e2e.RunCommand(ctx, "boundary", e2e.WithArgs("scopes", "delete", "-id", orgId))
require.NoError(t, output.Err, string(output.Stderr))
})
projectId, err := boundary.CreateProjectCli(t, ctx, orgId)
require.NoError(t, err)
targetId, err := boundary.CreateTargetCli(
t,
ctx,
projectId,
redisInfo.Port,
target.WithAddress(redisInfo.Hostname),
)
require.NoError(t, err)
storeId, err := boundary.CreateCredentialStoreStaticCli(t, ctx, projectId)
require.NoError(t, err)
credentialId, err := boundary.CreateStaticCredentialPasswordCli(
t,
ctx,
storeId,
redisInfo.Password,
)
require.NoError(t, err)
err = boundary.AddBrokeredCredentialSourceToTargetCli(t, ctx, targetId, credentialId)
require.NoError(t, err)
// Validate redis connect
cmd := exec.CommandContext(ctx,
"boundary",
"connect", "redis",
"-target-id", targetId,
)
stdin, err := cmd.StdinPipe()
require.NoError(t, err)
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
output, err := infra.SendRedisCommand(stdin, stdout, "ACL WHOAMI\r\n")
require.NoError(t, err)
require.Equal(t, "default", output) // redis default user
output, err = infra.SendRedisCommand(stdin, stdout, "SET e2etestkey e2etestvalue\r\n")
require.NoError(t, err)
require.Equal(t, "OK", output)
output, err = infra.SendRedisCommand(stdin, stdout, "GET e2etestkey\r\n")
require.NoError(t, err)
require.Equal(t, "e2etestvalue", output)
output, err = infra.SendRedisCommand(stdin, stdout, "QUIT\r\n")
require.Equal(t, io.EOF, err)
require.Empty(t, output)
// Confirm that boundary connect has closed
err = cmd.Wait()
require.NoError(t, err)
}
@@ -1,141 +0,0 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package base_test
import (
"context"
"io"
"net/url"
"os/exec"
"strings"
"testing"
"github.com/hashicorp/boundary/internal/target"
"github.com/hashicorp/boundary/testing/internal/e2e"
"github.com/hashicorp/boundary/testing/internal/e2e/boundary"
"github.com/hashicorp/boundary/testing/internal/e2e/infra"
"github.com/ory/dockertest/v3"
"github.com/stretchr/testify/require"
)
// TestCliTcpTargetConnectRedis uses the boundary cli to connect to a target using `connect redis`
func TestCliTcpTargetConnectRedis(t *testing.T) {
e2e.MaybeSkipTest(t)
pool, err := dockertest.NewPool("")
require.NoError(t, err)
ctx := context.Background()
network, err := pool.NetworksByName("e2e_cluster")
require.NoError(t, err, "Failed to get e2e_cluster network")
c := infra.StartRedis(t, pool, &network[0], "redis", "latest")
require.NotNil(t, c, "Redis container should not be nil")
t.Cleanup(func() {
if err := pool.Purge(c.Resource); err != nil {
t.Logf("Failed to purge Redis container: %v", err)
}
})
u, err := url.Parse(c.UriNetwork)
t.Log(u)
require.NoError(t, err, "Failed to parse Redis URL")
user, hostname, port := u.User.Username(), u.Hostname(), u.Port()
pw, pwSet := u.User.Password()
t.Logf("Redis info: user=%s, host=%s, port=%s, password-set:%t",
user, hostname, port, pwSet)
// Wait for Redis to be ready
err = pool.Retry(func() error {
out, e := exec.CommandContext(ctx, "docker", "exec", hostname,
"redis-cli", "-h", hostname, "-p", port, "PING").CombinedOutput()
t.Logf("Redis PING output: %s", out)
return e
})
require.NoError(t, err, "Redis container failed to start")
boundary.AuthenticateAdminCli(t, ctx)
orgId, err := boundary.CreateOrgCli(t, ctx)
require.NoError(t, err)
t.Cleanup(func() {
ctx := context.Background()
boundary.AuthenticateAdminCli(t, ctx)
output := e2e.RunCommand(ctx, "boundary", e2e.WithArgs("scopes", "delete", "-id", orgId))
require.NoError(t, output.Err, string(output.Stderr))
})
projectId, err := boundary.CreateProjectCli(t, ctx, orgId)
require.NoError(t, err)
targetId, err := boundary.CreateTargetCli(
t,
ctx,
projectId,
port,
[]target.Option{target.WithAddress(hostname)},
)
require.NoError(t, err)
storeId, err := boundary.CreateCredentialStoreStaticCli(t, ctx, projectId)
require.NoError(t, err)
credentialId, err := boundary.CreateStaticCredentialUsernamePasswordCli(
t,
ctx,
storeId,
user,
pw,
)
require.NoError(t, err)
err = boundary.AddBrokeredCredentialSourceToTargetCli(t, ctx, targetId, credentialId)
require.NoError(t, err)
t.Logf("Attempting to connect to Redis target %s", targetId)
cmd := exec.CommandContext(ctx,
"boundary",
"connect", "redis",
"-target-id", targetId,
)
stdin, err := cmd.StdinPipe()
require.NoError(t, err)
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
output, err := sendRedisCommand(stdin, stdout, "SET e2etestkey e2etestvalue\r\n")
require.NoError(t, err)
require.Equal(t, "OK", output)
output, err = sendRedisCommand(stdin, stdout, "GET e2etestkey\r\n")
require.NoError(t, err)
require.Equal(t, "e2etestvalue", output)
output, err = sendRedisCommand(stdin, stdout, "QUIT\r\n")
require.Equal(t, io.EOF, err)
require.Empty(t, output)
// Confirm that boundary connect has closed
err = cmd.Wait()
require.NoError(t, err)
}
func sendRedisCommand(stdin io.WriteCloser, stdout io.ReadCloser, cmdStr string) (string, error) {
_, err := stdin.Write([]byte(cmdStr))
if err != nil {
return "", err
}
buf := make([]byte, 1024)
n, err := stdout.Read(buf)
if err != nil {
return "", err
}
return strings.TrimSpace(string(buf[:n])), nil
}
@@ -0,0 +1,97 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package base_test
import (
"context"
"io"
"os/exec"
"testing"
"github.com/hashicorp/boundary/internal/target"
"github.com/hashicorp/boundary/testing/internal/e2e"
"github.com/hashicorp/boundary/testing/internal/e2e/boundary"
"github.com/hashicorp/boundary/testing/internal/e2e/infra"
"github.com/stretchr/testify/require"
)
// TestCliTcpTargetConnectRedisUsernamePassword uses the boundary cli to connect to a target
// using `connect redis` and a username-password credential.
func TestCliTcpTargetConnectRedisUsernamePassword(t *testing.T) {
e2e.MaybeSkipTest(t)
// Setup
ctx := context.Background()
redisInfo := infra.SetupRedisContainer(t)
boundary.AuthenticateAdminCli(t, ctx)
// Create Boundary resources
orgId, err := boundary.CreateOrgCli(t, ctx)
require.NoError(t, err)
t.Cleanup(func() {
ctx := context.Background()
boundary.AuthenticateAdminCli(t, ctx)
output := e2e.RunCommand(ctx, "boundary", e2e.WithArgs("scopes", "delete", "-id", orgId))
require.NoError(t, output.Err, string(output.Stderr))
})
projectId, err := boundary.CreateProjectCli(t, ctx, orgId)
require.NoError(t, err)
targetId, err := boundary.CreateTargetCli(
t,
ctx,
projectId,
redisInfo.Port,
[]target.Option{target.WithAddress(redisInfo.Hostname)},
)
require.NoError(t, err)
storeId, err := boundary.CreateCredentialStoreStaticCli(t, ctx, projectId)
require.NoError(t, err)
credentialId, err := boundary.CreateStaticCredentialUsernamePasswordCli(
t,
ctx,
storeId,
redisInfo.Username,
redisInfo.Password,
)
require.NoError(t, err)
err = boundary.AddBrokeredCredentialSourceToTargetCli(t, ctx, targetId, credentialId)
require.NoError(t, err)
// Validate redis connect
cmd := exec.CommandContext(ctx,
"boundary",
"connect", "redis",
"-target-id", targetId,
)
stdin, err := cmd.StdinPipe()
require.NoError(t, err)
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
output, err := infra.SendRedisCommand(stdin, stdout, "ACL WHOAMI\r\n")
require.NoError(t, err)
require.Equal(t, redisInfo.Username, output)
output, err = infra.SendRedisCommand(stdin, stdout, "SET e2etestkey e2etestvalue\r\n")
require.NoError(t, err)
require.Equal(t, "OK", output)
output, err = infra.SendRedisCommand(stdin, stdout, "GET e2etestkey\r\n")
require.NoError(t, err)
require.Equal(t, "e2etestvalue", output)
output, err = infra.SendRedisCommand(stdin, stdout, "QUIT\r\n")
require.Equal(t, io.EOF, err)
require.Empty(t, output)
// Confirm that boundary connect has closed
err = cmd.Wait()
require.NoError(t, err)
}