diff --git a/cmd/aws_devops_agent/status.go b/cmd/aws_devops_agent/status.go index 342e6db58..be31b1a46 100644 --- a/cmd/aws_devops_agent/status.go +++ b/cmd/aws_devops_agent/status.go @@ -92,7 +92,14 @@ func printStatus(out io.Writer, status awsdevops.Status) { } for _, space := range status.AgentSpaces { _, _ = fmt.Fprintf(out, "\nAgent space %s (%s)\n", space.Name, space.AgentSpaceID) - _, _ = fmt.Fprintf(out, " Operator app: %s\n", space.OperatorAppURL) + app := space.OperatorAppURL + switch { + case space.OperatorAppError != "": + app = "unknown (" + space.OperatorAppError + ")" + case !space.OperatorAppEnabled: + app = "off" + } + _, _ = fmt.Fprintf(out, " Operator app: %s\n", app) if len(space.Associations) > 0 { _, _ = fmt.Fprintln(out, " Connected to:") } diff --git a/cmd/aws_devops_agent/status_fixture_test.go b/cmd/aws_devops_agent/status_fixture_test.go index 747249a27..3e727c7bb 100644 --- a/cmd/aws_devops_agent/status_fixture_test.go +++ b/cmd/aws_devops_agent/status_fixture_test.go @@ -14,9 +14,10 @@ func realisticStatus() awsdevops.Status { {ServiceID: "s-ld01", ServiceType: "mcpserver", Name: "LaunchDarkly"}, }, AgentSpaces: []awsdevops.AgentSpaceStatus{{ - AgentSpaceID: "as-prod01", - Name: "Production", - OperatorAppURL: awsdevops.OperatorAppURL("as-prod01"), + AgentSpaceID: "as-prod01", + Name: "Production", + OperatorAppURL: awsdevops.OperatorAppURL("as-prod01"), + OperatorAppEnabled: true, Associations: []awsdevops.AssociationStatus{ {AssociationID: "a-001", ServiceID: "aws", Status: "valid", AccountID: "123456789012", AccountType: "monitor"}, {AssociationID: "a-002", ServiceID: "s-ld01", Status: "valid"}, @@ -36,9 +37,9 @@ func partialStatus() awsdevops.Status { {Name: awsdevops.OperatorAppRoleName}, }, AgentSpaces: []awsdevops.AgentSpaceStatus{{ - AgentSpaceID: "as-prod01", - Name: "Production", - OperatorAppURL: awsdevops.OperatorAppURL("as-prod01"), + AgentSpaceID: "as-prod01", + Name: "Production", + OperatorAppError: "AccessDeniedException", }}, MissingSetup: []string{"IAM role " + awsdevops.OperatorAppRoleName + " does not exist"}, } diff --git a/cmd/aws_devops_agent/status_test.go b/cmd/aws_devops_agent/status_test.go index 299739c52..276ac5647 100644 --- a/cmd/aws_devops_agent/status_test.go +++ b/cmd/aws_devops_agent/status_test.go @@ -253,6 +253,18 @@ func TestStatusFullSetupOmitsSetupHint(t *testing.T) { assert.NotContains(t, renderStatus(realisticStatus()), "ldcli aws-devops-agent setup") } +func TestStatusShowsAnUnknownOperatorApp(t *testing.T) { + status := realisticStatus() + space := &status.AgentSpaces[0] + space.OperatorAppEnabled = false + space.OperatorAppURL = "" + space.OperatorAppError = "AccessDeniedException" + section := spaceSection(t, renderStatus(status), "Production") + + assert.Equal(t, " Operator app: unknown (AccessDeniedException)", lineWith(t, section, "Operator app")) + assert.Contains(t, strings.Join(section, "\n"), "LaunchDarkly MCP server: ready") +} + func TestStatusJSONUnchanged(t *testing.T) { cases := map[string]awsdevops.Status{ "testdata/status.json": realisticStatus(), @@ -285,3 +297,15 @@ func TestStatusServicesListLabelsBlankService(t *testing.T) { } } } + +// An app that is off has no working URL. +func TestStatusShowsAnOperatorAppThatIsOff(t *testing.T) { + status := realisticStatus() + status.AgentSpaces[0].OperatorAppEnabled = false + status.AgentSpaces[0].OperatorAppURL = "" + + out := renderStatus(status) + + assert.Contains(t, out, "Operator app: off") + assert.NotContains(t, out, "aidevops.global.app.aws") +} diff --git a/cmd/aws_devops_agent/testdata/status-partial.json b/cmd/aws_devops_agent/testdata/status-partial.json index 3a6fc91a7..d54be8ce6 100644 --- a/cmd/aws_devops_agent/testdata/status-partial.json +++ b/cmd/aws_devops_agent/testdata/status-partial.json @@ -16,7 +16,9 @@ { "agentSpaceId": "as-prod01", "name": "Production", - "operatorAppUrl": "https://as-prod01.aidevops.global.app.aws" + "operatorAppUrl": "", + "operatorAppEnabled": false, + "operatorAppError": "AccessDeniedException" } ], "missingSetup": [ diff --git a/cmd/aws_devops_agent/testdata/status.json b/cmd/aws_devops_agent/testdata/status.json index 46b9c9cbd..ad232fdd5 100644 --- a/cmd/aws_devops_agent/testdata/status.json +++ b/cmd/aws_devops_agent/testdata/status.json @@ -25,6 +25,7 @@ "agentSpaceId": "as-prod01", "name": "Production", "operatorAppUrl": "https://as-prod01.aidevops.global.app.aws", + "operatorAppEnabled": true, "associations": [ { "associationId": "a-001", diff --git a/internal/awsdevops/awsdevops.go b/internal/awsdevops/awsdevops.go index 79aab94bd..72155518a 100644 --- a/internal/awsdevops/awsdevops.go +++ b/internal/awsdevops/awsdevops.go @@ -54,6 +54,8 @@ type AgentAPI interface { DeregisterService(context.Context, *devopsagent.DeregisterServiceInput, ...func(*devopsagent.Options)) (*devopsagent.DeregisterServiceOutput, error) DisassociateService(context.Context, *devopsagent.DisassociateServiceInput, ...func(*devopsagent.Options)) (*devopsagent.DisassociateServiceOutput, error) EnableOperatorApp(context.Context, *devopsagent.EnableOperatorAppInput, ...func(*devopsagent.Options)) (*devopsagent.EnableOperatorAppOutput, error) + GetOperatorApp(context.Context, *devopsagent.GetOperatorAppInput, ...func(*devopsagent.Options)) (*devopsagent.GetOperatorAppOutput, error) + ListTagsForResource(context.Context, *devopsagent.ListTagsForResourceInput, ...func(*devopsagent.Options)) (*devopsagent.ListTagsForResourceOutput, error) GetAgentSpace(context.Context, *devopsagent.GetAgentSpaceInput, ...func(*devopsagent.Options)) (*devopsagent.GetAgentSpaceOutput, error) ListAgentSpaces(context.Context, *devopsagent.ListAgentSpacesInput, ...func(*devopsagent.Options)) (*devopsagent.ListAgentSpacesOutput, error) ListAssociations(context.Context, *devopsagent.ListAssociationsInput, ...func(*devopsagent.Options)) (*devopsagent.ListAssociationsOutput, error) diff --git a/internal/awsdevops/awsdevops_test.go b/internal/awsdevops/awsdevops_test.go index d889f05b2..ff7193494 100644 --- a/internal/awsdevops/awsdevops_test.go +++ b/internal/awsdevops/awsdevops_test.go @@ -27,6 +27,15 @@ import ( const testAccountID = "123456789012" type fakeAgent struct { + // tags holds tags by resource ARN. + tags map[string]map[string]string + tagsErr error + // tagsErrFor fails the tag lookup of one resource ARN. + tagsErrFor map[string]error + // operatorApps holds enabled apps by space. + operatorApps map[string]*devopsagent.GetOperatorAppOutput + // operatorAppErr fails every GetOperatorApp call. + operatorAppErr error calls []string services []agenttypes.RegisteredService associationInputs []*devopsagent.AssociateServiceInput @@ -101,6 +110,31 @@ func (f *fakeAgent) DisassociateService(_ context.Context, in *devopsagent.Disas return &devopsagent.DisassociateServiceOutput{}, nil } +func (f *fakeAgent) GetOperatorApp(_ context.Context, in *devopsagent.GetOperatorAppInput, _ ...func(*devopsagent.Options)) (*devopsagent.GetOperatorAppOutput, error) { + f.calls = append(f.calls, "GetOperatorApp") + if f.operatorAppErr != nil { + return nil, f.operatorAppErr + } + app, ok := f.operatorApps[aws.ToString(in.AgentSpaceId)] + if !ok { + return nil, &agenttypes.ResourceNotFoundException{} + } + + return app, nil +} + +func (f *fakeAgent) ListTagsForResource(_ context.Context, in *devopsagent.ListTagsForResourceInput, _ ...func(*devopsagent.Options)) (*devopsagent.ListTagsForResourceOutput, error) { + f.calls = append(f.calls, "ListTagsForResource") + if f.tagsErr != nil { + return nil, f.tagsErr + } + if err := f.tagsErrFor[aws.ToString(in.ResourceArn)]; err != nil { + return nil, err + } + + return &devopsagent.ListTagsForResourceOutput{Tags: f.tags[aws.ToString(in.ResourceArn)]}, nil +} + func (f *fakeAgent) EnableOperatorApp(_ context.Context, _ *devopsagent.EnableOperatorAppInput, _ ...func(*devopsagent.Options)) (*devopsagent.EnableOperatorAppOutput, error) { f.calls = append(f.calls, "EnableOperatorApp") @@ -110,11 +144,18 @@ func (f *fakeAgent) EnableOperatorApp(_ context.Context, _ *devopsagent.EnableOp } func (f *fakeAgent) GetAgentSpace(_ context.Context, in *devopsagent.GetAgentSpaceInput, _ ...func(*devopsagent.Options)) (*devopsagent.GetAgentSpaceOutput, error) { + id := aws.ToString(in.AgentSpaceId) + name := "launchdarkly" + var description *string + for _, space := range f.agentSpaces { + if aws.ToString(space.AgentSpaceId) == id && space.Name != nil { + name = aws.ToString(space.Name) + description = space.Description + } + } + return &devopsagent.GetAgentSpaceOutput{ - AgentSpace: &agenttypes.AgentSpace{ - AgentSpaceId: in.AgentSpaceId, - Name: aws.String("launchdarkly"), - }, + AgentSpace: &agenttypes.AgentSpace{AgentSpaceId: in.AgentSpaceId, Name: aws.String(name), Description: description}, }, nil } diff --git a/internal/awsdevops/lookup.go b/internal/awsdevops/lookup.go index 7d6baa2d3..645b12d44 100644 --- a/internal/awsdevops/lookup.go +++ b/internal/awsdevops/lookup.go @@ -70,6 +70,112 @@ func listAssociations(ctx context.Context, clients Clients, agentSpaceID string) } } +// AgentSpaceSummary identifies an agent space the account already has, for a +// caller that has to pick one. +type AgentSpaceSummary struct { + AgentSpaceID string `json:"agentSpaceId"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + // ManagedByLDCLI means that setup made the space. + ManagedByLDCLI bool `json:"managedByLdcli"` + // TagErr is set if setup could not read the tags of the space. The owner + // of the space is then unknown, and ManagedByLDCLI is false. + TagErr error `json:"-"` +} + +// AgentSpaces lists the agent spaces in the account and region. A space that +// setup made has the ldcli:managed tag. A user can change the description, so +// only the tag counts. Each space costs one tag lookup. +// +// If a tag lookup fails, the summary of that space has TagErr, and the other +// spaces stay in the list. Setup uses the tag to decide if it can change the +// roles and the operator app of a space, so a caller must not use a space with +// TagErr as if its owner is known. If every lookup fails, for example without +// aidevops:ListTagsForResource, AgentSpaces returns the first error. The +// status command does not call AgentSpaces. +func AgentSpaces(ctx context.Context, clients Clients) ([]AgentSpaceSummary, error) { + spaces, err := listAgentSpaces(ctx, clients) + if err != nil || len(spaces) == 0 { + return nil, err + } + accountID, err := clients.AccountID(ctx) + if err != nil { + return nil, err + } + + summaries := make([]AgentSpaceSummary, 0, len(spaces)) + var firstErr error + failed := 0 + for _, space := range spaces { + summary := AgentSpaceSummary{ + AgentSpaceID: aws.ToString(space.AgentSpaceId), + Name: aws.ToString(space.Name), + Description: aws.ToString(space.Description), + } + summary.ManagedByLDCLI, summary.TagErr = hasManagedTag(ctx, clients, accountID, summary.AgentSpaceID) + if summary.TagErr != nil { + failed++ + if firstErr == nil { + firstErr = summary.TagErr + } + } + summaries = append(summaries, summary) + } + if failed == len(summaries) { + return nil, firstErr + } + + return summaries, nil +} + +// AgentSpace reads one agent space, with the same ownership check as +// AgentSpaces, for a caller that already has the space ID. If setup cannot +// read the tags, the summary has TagErr. +func AgentSpace(ctx context.Context, clients Clients, spaceID string) (AgentSpaceSummary, error) { + out, err := clients.Agent.GetAgentSpace(ctx, &devopsagent.GetAgentSpaceInput{AgentSpaceId: aws.String(spaceID)}) + if err != nil { + return AgentSpaceSummary{}, fmt.Errorf("unable to read agent space %s: %w", spaceID, err) + } + accountID, err := clients.AccountID(ctx) + if err != nil { + return AgentSpaceSummary{}, err + } + summary := AgentSpaceSummary{ + AgentSpaceID: spaceID, + Name: aws.ToString(out.AgentSpace.Name), + Description: aws.ToString(out.AgentSpace.Description), + } + // A tag error goes on the summary, as in AgentSpaces. The caller decides + // what to do with a space whose owner is unknown. + summary.ManagedByLDCLI, summary.TagErr = hasManagedTag(ctx, clients, accountID, spaceID) + + return summary, nil +} + +// hasManagedTag reports the ldcli:managed tag on an agent space. +func hasManagedTag(ctx context.Context, clients Clients, accountID, spaceID string) (bool, error) { + out, err := clients.Agent.ListTagsForResource(ctx, &devopsagent.ListTagsForResourceInput{ + ResourceArn: aws.String(agentSpaceARN(clients.Region, accountID, spaceID)), + }) + // The SDK retries a throttle or a server error before it returns. Only an + // access error points to the permission. + if err != nil && errorCode(err) == "AccessDeniedException" { + return false, fmt.Errorf( + "unable to read the tags of agent space %s. Setup needs aidevops:ListTagsForResource: %w", spaceID, err) + } + if err != nil { + return false, fmt.Errorf("unable to read the tags of agent space %s: %w", spaceID, err) + } + + return out.Tags[ManagedTagKey] == ManagedTagValue, nil +} + +// agentSpaceARN builds the ARN that the tag API needs. An agent space does not +// report its ARN. +func agentSpaceARN(region, accountID, spaceID string) string { + return fmt.Sprintf("arn:aws:aidevops:%s:%s:agentspace/%s", region, accountID, spaceID) +} + // FindMCPServer returns the ID of the MCP server registered at endpoint, if the // account has one. AWS keeps MCP servers at the account level, so a second // agent space reuses the existing registration. diff --git a/internal/awsdevops/lookup_test.go b/internal/awsdevops/lookup_test.go index 8457ef052..3532bd102 100644 --- a/internal/awsdevops/lookup_test.go +++ b/internal/awsdevops/lookup_test.go @@ -2,10 +2,12 @@ package awsdevops_test import ( "context" + "errors" "net/http" "testing" "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/devopsagent" agenttypes "github.com/aws/aws-sdk-go-v2/service/devopsagent/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -73,3 +75,211 @@ func TestFindMCPServerMatchesOnTheEndpointInTheServiceDetails(t *testing.T) { assert.Equal(t, "mcp-2", serviceID) } + +const space1ARN = "arn:aws:aidevops:us-east-1:" + testAccountID + ":agentspace/space-1" + +var spaceTags = map[string]string{awsdevops.ManagedTagKey: awsdevops.ManagedTagValue} + +func TestAgentSpacesListsEveryPage(t *testing.T) { + agent := &fakeAgent{ + paginate: true, + agentSpaces: []agenttypes.AgentSpace{ + {AgentSpaceId: aws.String("space-1"), Name: aws.String("launchdarkly"), Description: aws.String("Managed by the LaunchDarkly CLI")}, + {AgentSpaceId: aws.String("space-2"), Name: aws.String("platform"), Description: aws.String("Team space")}, + }, + tags: map[string]map[string]string{space1ARN: spaceTags}, + } + + spaces, err := awsdevops.AgentSpaces(context.Background(), newTestClients(agent, newFakeIAM())) + require.NoError(t, err) + + assert.Equal(t, []awsdevops.AgentSpaceSummary{ + {AgentSpaceID: "space-1", Name: "launchdarkly", Description: "Managed by the LaunchDarkly CLI", ManagedByLDCLI: true}, + {AgentSpaceID: "space-2", Name: "platform", Description: "Team space"}, + }, spaces) +} + +// A user can change the description, so only the tag counts. +func TestAgentSpacesCountsOnlyTheTag(t *testing.T) { + agent := &fakeAgent{agentSpaces: []agenttypes.AgentSpace{ + {AgentSpaceId: aws.String("space-1"), Name: aws.String("copy"), Description: aws.String("Managed by the LaunchDarkly CLI")}, + {AgentSpaceId: aws.String("space-2"), Name: aws.String("tagged"), Description: aws.String("Renamed by a user")}, + }} + agent.tags = map[string]map[string]string{ + "arn:aws:aidevops:us-east-1:" + testAccountID + ":agentspace/space-2": spaceTags, + } + + spaces, err := awsdevops.AgentSpaces(context.Background(), newTestClients(agent, newFakeIAM())) + require.NoError(t, err) + + assert.False(t, spaces[0].ManagedByLDCLI) + assert.True(t, spaces[1].ManagedByLDCLI) + assert.Equal(t, 2, countCalls(agent.calls, "ListTagsForResource")) +} + +// If every lookup fails, AgentSpaces fails. +func TestAgentSpacesReportsATagError(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{ + {AgentSpaceId: aws.String("space-1"), Name: aws.String("launchdarkly"), Description: aws.String("Managed by the LaunchDarkly CLI")}, + }, + tagsErr: apiError{code: "AccessDeniedException"}, + } + + _, err := awsdevops.AgentSpaces(context.Background(), newTestClients(agent, newFakeIAM())) + + require.Error(t, err) + assert.Contains(t, err.Error(), "tags of agent space space-1") + assert.Contains(t, err.Error(), "aidevops:ListTagsForResource") +} + +// One failed lookup does not hide the other spaces. +func TestAgentSpacesKeepsTheSpacesWithATag(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "launchdarkly"), namedSpace("space-2", "sandbox")}, + tags: map[string]map[string]string{space1ARN: spaceTags}, + tagsErrFor: map[string]error{ + "arn:aws:aidevops:us-east-1:" + testAccountID + ":agentspace/space-2": apiError{code: "InternalServerException"}, + }, + } + + spaces, err := awsdevops.AgentSpaces(context.Background(), newTestClients(agent, newFakeIAM())) + + require.NoError(t, err) + require.Len(t, spaces, 2) + assert.True(t, spaces[0].ManagedByLDCLI) + assert.NoError(t, spaces[0].TagErr) + assert.Equal(t, "sandbox", spaces[1].Name) + assert.False(t, spaces[1].ManagedByLDCLI) + assert.ErrorContains(t, spaces[1].TagErr, "tags of agent space space-2") +} + +// A caller with a space ID gets the space even if its tags cannot be read. +func TestAgentSpaceReportsATagErrorOnTheSummary(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "launchdarkly")}, + tagsErr: apiError{code: "AccessDeniedException"}, + } + + space, err := awsdevops.AgentSpace(context.Background(), newTestClients(agent, newFakeIAM()), "space-1") + + require.NoError(t, err) + assert.Equal(t, "launchdarkly", space.Name) + assert.False(t, space.ManagedByLDCLI) + assert.ErrorContains(t, space.TagErr, "aidevops:ListTagsForResource") +} + +// Another error does not blame a missing permission. +func TestAgentSpacesReportsAnotherTagErrorWithoutThePermission(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "launchdarkly")}, + tagsErr: apiError{code: "InternalServerException"}, + } + + _, err := awsdevops.AgentSpaces(context.Background(), newTestClients(agent, newFakeIAM())) + + require.Error(t, err) + assert.Equal(t, "unable to read the tags of agent space space-1: api error InternalServerException", err.Error()) +} + +func countCalls(calls []string, name string) int { + n := 0 + for _, call := range calls { + if call == name { + n++ + } + } + + return n +} + +func TestStatusReadsTheOperatorApp(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "on"), namedSpace("space-2", "off")}, + operatorApps: map[string]*devopsagent.GetOperatorAppOutput{ + "space-1": {Iam: &agenttypes.IamAuthConfiguration{}}, + }, + } + + status, err := awsdevops.GetStatus(context.Background(), newTestClients(agent, newFakeIAM()), "") + require.NoError(t, err) + + require.Len(t, status.AgentSpaces, 2) + assert.True(t, status.AgentSpaces[0].OperatorAppEnabled) + assert.Equal(t, awsdevops.OperatorAppURL("space-1"), status.AgentSpaces[0].OperatorAppURL) + assert.False(t, status.AgentSpaces[1].OperatorAppEnabled) + assert.Empty(t, status.AgentSpaces[1].OperatorAppURL) +} + +// apiError acts like an AWS API error with a code. +type apiError struct{ code string } + +func (e apiError) Error() string { return "api error " + e.code } +func (e apiError) ErrorCode() string { return e.code } + +// A policy without aidevops:GetOperatorApp must not hide the rest of status. +func TestStatusReportsAnUnreadableAppAsUnknown(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "on")}, + operatorAppErr: apiError{code: "AccessDeniedException"}, + associations: []agenttypes.Association{{AssociationId: aws.String("assoc-1"), ServiceId: aws.String("mcp-1")}}, + } + + status, err := awsdevops.GetStatus(context.Background(), newTestClients(agent, newFakeIAM()), "") + require.NoError(t, err) + + require.Len(t, status.AgentSpaces, 1) + space := status.AgentSpaces[0] + assert.Equal(t, "AccessDeniedException", space.OperatorAppError) + assert.False(t, space.OperatorAppEnabled) + assert.Empty(t, space.OperatorAppURL) + assert.Len(t, space.Associations, 1) + assert.Len(t, status.Roles, 2) +} + +func TestStatusReportsTheErrorTextWithoutACode(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "on")}, + operatorAppErr: errors.New("connection reset"), + } + + status, err := awsdevops.GetStatus(context.Background(), newTestClients(agent, newFakeIAM()), "") + require.NoError(t, err) + + assert.Contains(t, status.AgentSpaces[0].OperatorAppError, "connection reset") +} + +// status and setup show the URL that AWS sends. +func TestStatusUsesTheOperatorAppURLFromAWS(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "on")}, + operatorApps: map[string]*devopsagent.GetOperatorAppOutput{ + "space-1": {Iam: &agenttypes.IamAuthConfiguration{}, OperatorAppUrl: aws.String("https://app.example.aws")}, + }, + } + + status, err := awsdevops.GetStatus(context.Background(), newTestClients(agent, newFakeIAM()), "") + require.NoError(t, err) + + assert.Equal(t, "https://app.example.aws", status.AgentSpaces[0].OperatorAppURL) +} + +func TestAgentSpaceReadsTheTagOfOneSpace(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{ + {AgentSpaceId: aws.String("space-1"), Name: aws.String("launchdarkly"), Description: aws.String("Managed by the LaunchDarkly CLI")}, + }, + tags: map[string]map[string]string{space1ARN: spaceTags}, + } + + space, err := awsdevops.AgentSpace(context.Background(), newTestClients(agent, newFakeIAM()), "space-1") + require.NoError(t, err) + + assert.True(t, space.ManagedByLDCLI) + assert.Equal(t, "launchdarkly", space.Name) + assert.NotContains(t, agent.calls, "ListAgentSpaces") +} + +func namedSpace(id, name string) agenttypes.AgentSpace { + return agenttypes.AgentSpace{AgentSpaceId: aws.String(id), Name: aws.String(name)} +} diff --git a/internal/awsdevops/setup.go b/internal/awsdevops/setup.go index a270a39d9..8f379710c 100644 --- a/internal/awsdevops/setup.go +++ b/internal/awsdevops/setup.go @@ -92,6 +92,48 @@ type SetupResult struct { MCPAssociationID string `json:"mcpAssociationId,omitempty"` } +// AppAction is the planned operator app action. +type AppAction int + +const ( + AppEnable AppAction = iota + AppKeep + AppChange +) + +// AppStep is the planned operator app step. +type AppStep struct { + Action AppAction + URL string + // Flow is the sign-in at plan time. + Flow string +} + +// appState reads the app. Flow "" means off. The space must exist. AWS sends +// ResourceNotFoundException for an app that is off and for a space that does +// not exist, so appState cannot tell the two apart. +func appState(ctx context.Context, clients Clients, spaceID string) (AppStep, error) { + app, err := clients.Agent.GetOperatorApp(ctx, &devopsagent.GetOperatorAppInput{AgentSpaceId: aws.String(spaceID)}) + var missing *agenttypes.ResourceNotFoundException + switch { + case errors.As(err, &missing): + return AppStep{}, nil + case err != nil: + return AppStep{}, fmt.Errorf("unable to read the operator app of agent space %s: %w", spaceID, err) + } + state := AppStep{URL: aws.ToString(app.OperatorAppUrl)} + switch { + case app.Idc != nil: + state.Flow = "idc" + case app.Idp != nil: + state.Flow = "idp" + case app.Iam != nil: + state.Flow = "iam" + } + + return state, nil +} + // Setup provisions the IAM roles, agent space, service associations and the // MCP server the AWS DevOps Agent needs to manage LaunchDarkly flags. func Setup(ctx context.Context, clients Clients, opts SetupOptions) (SetupResult, error) { diff --git a/internal/awsdevops/status.go b/internal/awsdevops/status.go index 755a08af2..c8265f0f6 100644 --- a/internal/awsdevops/status.go +++ b/internal/awsdevops/status.go @@ -2,6 +2,7 @@ package awsdevops import ( "context" + "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" @@ -36,10 +37,16 @@ type ServiceStatus struct { } type AgentSpaceStatus struct { - AgentSpaceID string `json:"agentSpaceId"` - Name string `json:"name"` - OperatorAppURL string `json:"operatorAppUrl"` - Associations []AssociationStatus `json:"associations,omitempty"` + AgentSpaceID string `json:"agentSpaceId"` + Name string `json:"name"` + OperatorAppURL string `json:"operatorAppUrl"` + // OperatorAppEnabled is false if the app is off. The URL is then empty. + OperatorAppEnabled bool `json:"operatorAppEnabled"` + // OperatorAppError is set if status could not read the app, for example + // without aidevops:GetOperatorApp. The state of the app is then unknown, + // and OperatorAppEnabled is false. + OperatorAppError string `json:"operatorAppError,omitempty"` + Associations []AssociationStatus `json:"associations,omitempty"` } type AssociationStatus struct { @@ -107,9 +114,21 @@ func GetStatus(ctx context.Context, clients Clients, agentSpaceID string) (Statu return status, fmt.Errorf("unable to read agent space %s: %w", id, err) } spaceStatus := AgentSpaceStatus{ - AgentSpaceID: id, - Name: aws.ToString(space.AgentSpace.Name), - OperatorAppURL: OperatorAppURL(id), + AgentSpaceID: id, + Name: aws.ToString(space.AgentSpace.Name), + } + // status is a read command. If it cannot read the app, it reports the + // app as unknown and shows the rest of the space. + app, err := appState(ctx, clients, id) + switch { + case err != nil: + spaceStatus.OperatorAppError = errorCode(err) + case app.Flow != "": + spaceStatus.OperatorAppEnabled = true + spaceStatus.OperatorAppURL = app.URL + if spaceStatus.OperatorAppURL == "" { + spaceStatus.OperatorAppURL = OperatorAppURL(id) + } } associations, err := listAssociations(ctx, clients, id) @@ -146,3 +165,14 @@ func associationAccount(configuration agenttypes.ServiceConfiguration) (accountI return "", "" } + +// errorCode gives the AWS error code, for example AccessDeniedException, or +// the error text if the error has no code. +func errorCode(err error) string { + var api interface{ ErrorCode() string } + if errors.As(err, &api) && api.ErrorCode() != "" { + return api.ErrorCode() + } + + return err.Error() +}