Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ The AWS DevOps Agent is available in `us-east-1`, `us-east-2`, `us-west-2`, `ca-

If the account already runs the AWS DevOps Agent, `setup` lists its agent spaces and asks which one to connect LaunchDarkly to. It then only registers and associates the LaunchDarkly MCP server on the space you pick, leaving its IAM roles, account association and operator app sign-in configuration alone. Pass `--agent-space-id <id>` to pick one without being asked, or `--new-agent-space` to provision another space.

If the SSO session of your profile expired, `setup` and `status` offer to run `aws sso login --profile <name>` for you. They ask only in a terminal.

Without a terminal — in CI, or with `--output json` — `setup` reuses the space matching `--agent-space-name` so an unattended re-run stays idempotent, and fails asking for `--agent-space-id` or `--new-agent-space` when the only spaces are ones it did not create.

Otherwise `setup` is safe to re-run: it reuses the IAM roles, the agent space, the account and MCP associations on it, and any LaunchDarkly MCP server already registered on the account. The IAM roles are account-wide and trust the agent spaces in every region, so running `setup` in a second region leaves the first one working; a role named `DevOpsAgentRole-AgentSpace` or `DevOpsAgentRole-WebappAdmin` that `setup` did not create is reused untouched, and it has to trust `aidevops.amazonaws.com` itself.
Expand Down
78 changes: 78 additions & 0 deletions cmd/aws_devops_agent/clients.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package awsdevopsagent

import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"

"github.com/spf13/cobra"

"github.com/launchdarkly/ldcli/internal/awsdevops"
)

// ssoLogin offers aws sso login on expired credentials.
type ssoLogin struct {
newClients func(ctx context.Context, region, profile string) (awsdevops.Clients, error)
configPath string
in io.Reader
out io.Writer
interactive func() bool
lookPath func(string) (string, error)
run func(ctx context.Context, name string, args ...string) error
}

// loadClients builds AWS clients from the command flags.
func loadClients(cmd *cobra.Command) (awsdevops.Clients, error) {
l := ssoLogin{
newClients: awsdevops.NewClients,
configPath: awsdevops.ConfigFilePath(),
in: cmd.InOrStdin(),
out: cmd.ErrOrStderr(),
interactive: canPrompt,
lookPath: exec.LookPath,
run: runAttached,
}

return l.clients(cmd.Context(), mustString(cmd, regionFlag), mustString(cmd, profileFlag))
}

func (l ssoLogin) clients(ctx context.Context, region, profile string) (awsdevops.Clients, error) {
clients, err := l.newClients(ctx, region, profile)
if !errors.Is(err, awsdevops.ErrNoCredentials) {
return clients, err
}

name := awsdevops.SSOProfile(l.configPath, profile)
if name == "" || !l.interactive() {
return clients, err
}
if _, lookErr := l.lookPath("aws"); lookErr != nil {
return clients, err
}

_, _ = fmt.Fprintf(l.out, "Run aws sso login --profile %s now? [y/N] ", name)
answer := strings.ToLower(readLine(l.in))
if answer != "y" && answer != "yes" {
return clients, err
}

if runErr := l.run(ctx, "aws", "sso", "login", "--profile", name); runErr != nil {
return awsdevops.Clients{}, fmt.Errorf("aws sso login --profile %s failed: %w", name, runErr)
}

return l.newClients(ctx, region, profile)
}

// runAttached runs a command on the terminal.
func runAttached(ctx context.Context, name string, args ...string) error {
c := exec.CommandContext(ctx, name, args...)
c.Stdin = os.Stdin
c.Stdout = os.Stderr // keep stdout for results
c.Stderr = os.Stderr

return c.Run()
}
230 changes: 230 additions & 0 deletions cmd/aws_devops_agent/clients_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
package awsdevopsagent

import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/launchdarkly/ldcli/internal/awsdevops"
)

type loginFake struct {
results []error
calls int
runs [][]string
runErr error
reads int
prompted *bytes.Buffer
}

func (f *loginFake) newClients(context.Context, string, string) (awsdevops.Clients, error) {
err := f.results[min(f.calls, len(f.results)-1)]
f.calls++
if err != nil {
return awsdevops.Clients{}, err
}

return awsdevops.Clients{Region: "us-east-1"}, nil
}

func (f *loginFake) run(_ context.Context, name string, args ...string) error {
f.runs = append(f.runs, append([]string{name}, args...))

return f.runErr
}

type countingReader struct {
f *loginFake
r io.Reader
}

func (c countingReader) Read(p []byte) (int, error) {
c.f.reads++

return c.r.Read(p)
}

var errCreds = fmt.Errorf("wrapped: %w", awsdevops.ErrNoCredentials)

const ssoConfig = "[profile dev]\nregion = us-east-1\n\n[profile dev-admin]\nsso_session = corp\n\n[profile sso]\nsso_session = corp\n"

func newLoginTest(t *testing.T, answer string, results ...error) (*loginFake, ssoLogin) {
t.Helper()
t.Setenv("AWS_PROFILE", "")
path := filepath.Join(t.TempDir(), "config")
require.NoError(t, os.WriteFile(path, []byte(ssoConfig), 0o600))
f := &loginFake{results: results, prompted: &bytes.Buffer{}}

return f, ssoLogin{
newClients: f.newClients,
configPath: path,
in: countingReader{f: f, r: strings.NewReader(answer)},
out: f.prompted,
interactive: func() bool { return true },
lookPath: func(string) (string, error) { return "/usr/local/bin/aws", nil },
run: f.run,
}
}

func TestLoginRunsOnceOnUppercaseY(t *testing.T) {
f, l := newLoginTest(t, "Y\n", errCreds, nil)

clients, err := l.clients(context.Background(), "", "sso")

require.NoError(t, err)
assert.Equal(t, "us-east-1", clients.Region)
assert.Equal(t, [][]string{{"aws", "sso", "login", "--profile", "sso"}}, f.runs)
assert.Equal(t, 2, f.calls)
assert.Contains(t, f.prompted.String(), "Run aws sso login --profile sso now? [y/N]")
}

func TestLoginAcceptsYesWithSpaces(t *testing.T) {
f, l := newLoginTest(t, " YeS \n", errCreds, nil)

_, err := l.clients(context.Background(), "", "sso")

require.NoError(t, err)
assert.Len(t, f.runs, 1)
}

func TestLoginIgnoresOtherAnswers(t *testing.T) {
for _, answer := range []string{"ye\n", "yess\n", "n\n", "\n", ""} {
t.Run(fmt.Sprintf("%q", answer), func(t *testing.T) {
f, l := newLoginTest(t, answer, errCreds, nil)

_, err := l.clients(context.Background(), "", "sso")

assert.Same(t, errCreds, err)
assert.Empty(t, f.runs)
assert.Equal(t, 1, f.calls)
})
}
}

func TestLoginRetriesOnlyOnce(t *testing.T) {
second := fmt.Errorf("again: %w", awsdevops.ErrNoCredentials)
f, l := newLoginTest(t, "y\ny\ny\n", errCreds, second)

_, err := l.clients(context.Background(), "", "sso")

assert.Same(t, second, err)
assert.Equal(t, 2, f.calls)
assert.Len(t, f.runs, 1)
}

func TestLoginFailureNamesTheCommand(t *testing.T) {
f, l := newLoginTest(t, "y\n", errCreds, nil)
f.runErr = errors.New("exit status 255")

_, err := l.clients(context.Background(), "", "sso")

require.Error(t, err)
assert.Contains(t, err.Error(), "aws sso login --profile sso")
assert.ErrorIs(t, err, f.runErr)
assert.Equal(t, 1, f.calls)
}

func TestLoginSkipsNearMissProfile(t *testing.T) {
f, l := newLoginTest(t, "y\n", errCreds, nil)

_, err := l.clients(context.Background(), "", "dev")

assert.Same(t, errCreds, err)
assert.Zero(t, f.reads)
assert.Empty(t, f.runs)
}

func TestLoginSkipsWithoutTerminal(t *testing.T) {
f, l := newLoginTest(t, "y\n", errCreds, nil)
l.interactive = func() bool { return false }

_, err := l.clients(context.Background(), "", "sso")

assert.Same(t, errCreds, err)
assert.Zero(t, f.reads)
assert.Empty(t, f.runs)
assert.Equal(t, 1, f.calls)
}

func TestLoginSkipsWithoutAWSBinary(t *testing.T) {
f, l := newLoginTest(t, "y\n", errCreds, nil)
l.lookPath = func(string) (string, error) { return "", errors.New("not found") }

_, err := l.clients(context.Background(), "", "sso")

assert.Same(t, errCreds, err)
assert.Zero(t, f.reads)
assert.Empty(t, f.runs)
}

func TestLoginSkipsOtherErrors(t *testing.T) {
regionErr := errors.New("AWS DevOps Agent is not available in us-east-3")
f, l := newLoginTest(t, "y\n", regionErr, nil)

_, err := l.clients(context.Background(), "", "sso")

assert.Same(t, regionErr, err)
assert.Zero(t, f.reads)
assert.Empty(t, f.runs)
assert.Equal(t, 1, f.calls)
}

func TestLoginSkipsWithoutProfile(t *testing.T) {
f, l := newLoginTest(t, "y\n", errCreds, nil)

_, err := l.clients(context.Background(), "", "")

assert.Same(t, errCreds, err)
assert.Zero(t, f.reads)
assert.Empty(t, f.runs)
}

// Without --profile or AWS_PROFILE, the SDK uses the default profile.
func TestLoginOffersTheDefaultSSOProfile(t *testing.T) {
f, l := newLoginTest(t, "y\n", errCreds, nil)
require.NoError(t, os.WriteFile(l.configPath, []byte("[default]\nsso_session = corp\n"), 0o600))

_, err := l.clients(context.Background(), "", "")

require.NoError(t, err)
assert.Equal(t, [][]string{{"aws", "sso", "login", "--profile", "default"}}, f.runs)
}

func TestLoginUsesAWSProfileVariable(t *testing.T) {
f, l := newLoginTest(t, "y\n", errCreds, nil)
t.Setenv("AWS_PROFILE", "sso")

_, err := l.clients(context.Background(), "", "")

require.NoError(t, err)
assert.Equal(t, [][]string{{"aws", "sso", "login", "--profile", "sso"}}, f.runs)
}

func TestLoginFlagWinsOverAWSProfile(t *testing.T) {
f, l := newLoginTest(t, "y\n", errCreds, nil)
t.Setenv("AWS_PROFILE", "sso")

_, err := l.clients(context.Background(), "", "dev")

assert.Same(t, errCreds, err)
assert.Empty(t, f.runs)
}

func TestLoginSkipsWhenFirstCallWorks(t *testing.T) {
f, l := newLoginTest(t, "y\n", nil)

_, err := l.clients(context.Background(), "", "sso")

require.NoError(t, err)
assert.Zero(t, f.reads)
assert.Equal(t, 1, f.calls)
}
2 changes: 1 addition & 1 deletion cmd/aws_devops_agent/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func runSetup(cmd *cobra.Command, args []string) error {
return err
}

clients, err := awsdevops.NewClients(cmd.Context(), mustString(cmd, regionFlag), mustString(cmd, profileFlag))
clients, err := loadClients(cmd)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/aws_devops_agent/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func NewStatusCmd(analyticsTrackerFn analytics.TrackerFn) *cobra.Command {
}

func runStatus(cmd *cobra.Command, args []string) error {
clients, err := awsdevops.NewClients(cmd.Context(), mustString(cmd, regionFlag), mustString(cmd, profileFlag))
clients, err := loadClients(cmd)
if err != nil {
return err
}
Expand Down
21 changes: 19 additions & 2 deletions internal/awsdevops/awsdevops.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,20 @@ func noCredentialsError(profile string, cause error) error {

var msg string
profiles := knownProfiles()
sso := SSOProfile(ConfigFilePath(), profile)
switch {
case active != "":
case sso != "":
msg = fmt.Sprintf(
"no AWS credentials for profile %q. Run `aws sso login --profile %s`, then run this command again",
active, active,
sso, sso,
)
case active != "" && cause != nil && !fromIMDS(cause):
// Only the cause tells what failed, for example a credential_process.
msg = fmt.Sprintf("unable to get AWS credentials for profile %q: %v", active, cause)
case active != "":
msg = fmt.Sprintf(
"profile %q has no AWS credentials. Add credentials to it, or pass --profile with another profile",
active,
)
case len(profiles) > 0:
msg = fmt.Sprintf(
Expand All @@ -186,6 +195,14 @@ func noCredentialsError(profile string, cause error) error {
return &noCredsErr{msg: msg, cause: cause}
}

// fromIMDS reports a cause from the EC2 metadata service. The SDK tries it
// last, so its error only says that no other source had credentials.
func fromIMDS(err error) bool {
var op interface{ Service() string }

return errors.As(err, &op) && op.Service() == "ec2imds"
}

// summarizeProfiles lists the first few names.
func summarizeProfiles(profiles []string) string {
if len(profiles) <= maxListedProfiles {
Expand Down
5 changes: 3 additions & 2 deletions internal/awsdevops/awsdevops_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,7 @@ func TestNewClientsNamesTheSelectedProfile(t *testing.T) {
_, err := awsdevops.NewClients(context.Background(), "us-east-1", "my-profile")

assert.ErrorIs(t, err, awsdevops.ErrNoCredentials)
assert.ErrorContains(t, err, `profile "my-profile"`)
assert.ErrorContains(t, err, "aws sso login --profile my-profile")
assert.ErrorContains(t, err, `profile "my-profile" has no AWS credentials`)
assert.NotContains(t, err.Error(), "sso login")
assert.NotContains(t, err.Error(), "ec2imds")
}
Loading
Loading