From b6a8aa27ede10a2b13968c14de13c04e2ca3acae Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Thu, 28 Mar 2024 14:13:42 -0400 Subject: [PATCH 01/26] wip --- cloud/organization/organization_token.go | 126 +++++++++++++++++++++-- cloud/workspace/workspace_token.go | 108 ++++++++++++++++++- 2 files changed, 225 insertions(+), 9 deletions(-) diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index 16e521071..d8aeb7826 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -21,10 +21,12 @@ var ( ErrInvalidName = errors.New("no name provided for the organization token. Retry with a valid name") errInvalidOrganizationTokenKey = errors.New("invalid Organization API token selection") errOrganizationTokenNotFound = errors.New("organization token specified was not found") - errOrgTokenInWorkspace = errors.New("this Organization API token has already been added to the Workspace") + errOrgTokenInWorkspace = errors.New("this Organization API token has already been added to the Workspace with that role") + errOrgTokenInDeployment = errors.New("this Organization API token has already been added to the Deployment with that role") ) const ( + deploymentEntity = "DEPLOYMENT" workspaceEntity = "WORKSPACE" organizationEntity = "ORGANIZATION" ) @@ -81,24 +83,126 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli apiTokenID := token.Id var orgRole string + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} + apiTokenWorkspaceRole := astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: workspace, + Role: role, + } + apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} + for i := range token.Roles { if token.Roles[i].EntityId == workspace { - return errOrgTokenInWorkspace + if token.Roles[i].Role == role { + return errOrgTokenInWorkspace + } else { + continue + } } if token.Roles[i].EntityId == ctx.Organization { orgRole = token.Roles[i].Role } + + if token.Roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: token.Roles[i].EntityId, + Role: token.Roles[i].Role, + }) + } + if token.Roles[i].EntityType == workspaceEntity { + apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: token.Roles[i].EntityId, + Role: token.Roles[i].Role, + }) + } } - apiTokenWorkspaceRole := astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: workspace, + updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ + Organization: orgRole, + Workspace: &apiTokenWorkspaceRoles, + Deployment: &apiTokenDeploymentRoles, + } + updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ + Name: token.Name, + Description: token.Description, + Roles: updateOrganizationAPITokenRoles, + } + + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) + if err != nil { + return err + } + err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return err + } + fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Workspace\n", token.Name) + return nil +} + +func AddOrgTokenToDeployment(id, name, role, deployment string, out io.Writer, client astrocore.CoreClient) error { + ctx, err := context.GetCurrentContext() + if err != nil { + return err + } + + var token astrocore.ApiToken + if id == "" { + tokens, err := getOrganizationTokens(client) + if err != nil { + return err + } + token, err = getOrganizationToken(id, name, "\nPlease select the Organization API token you would like to add to the Deployment:", tokens) + if err != nil { + return err + } + } else { + token, err = getOrganizationTokenByID(id, ctx.Organization, client) + if err != nil { + return err + } + } + + apiTokenID := token.Id + var orgRole string + apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} + apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: deployment, Role: role, } - apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} + + for i := range token.Roles { + if token.Roles[i].EntityId == deployment { + if token.Roles[i].Role == role { + return errOrgTokenInDeployment + } else { + continue + } + } + + if token.Roles[i].EntityId == ctx.Organization { + orgRole = token.Roles[i].Role + } + + if token.Roles[i].EntityType == workspaceEntity { + apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: token.Roles[i].EntityId, + Role: token.Roles[i].Role, + }) + } + + if token.Roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: token.Roles[i].EntityId, + Role: token.Roles[i].Role, + }) + } + } updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ Organization: orgRole, + Deployment: &apiTokenDeploymentRoles, Workspace: &apiTokenWorkspaceRoles, } updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ @@ -115,7 +219,7 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli if err != nil { return err } - fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Workspace\n", token.Name) + fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) return nil } @@ -383,6 +487,7 @@ func UpdateToken(id, name, newName, description, role string, out io.Writer, cli var currentOrgRole string apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} for i := range token.Roles { if token.Roles[i].EntityType == workspaceEntity { @@ -392,6 +497,13 @@ func UpdateToken(id, name, newName, description, role string, out io.Writer, cli }) } + if token.Roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: token.Roles[i].EntityId, + Role: token.Roles[i].Role, + }) + } + if token.Roles[i].EntityType == organizationEntity { currentOrgRole = token.Roles[i].Role } @@ -400,6 +512,7 @@ func UpdateToken(id, name, newName, description, role string, out io.Writer, cli updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ Organization: currentOrgRole, Workspace: &apiTokenWorkspaceRoles, + Deployment: &apiTokenDeploymentRoles, } UpdateOrganizationAPITokenRequest.Roles = updateOrganizationAPITokenRoles @@ -411,6 +524,7 @@ func UpdateToken(id, name, newName, description, role string, out io.Writer, cli updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ Organization: role, Workspace: &apiTokenWorkspaceRoles, + Deployment: &apiTokenDeploymentRoles, } UpdateOrganizationAPITokenRequest.Roles = updateOrganizationAPITokenRoles } diff --git a/cloud/workspace/workspace_token.go b/cloud/workspace/workspace_token.go index ce58b6a5c..ca6b911c2 100644 --- a/cloud/workspace/workspace_token.go +++ b/cloud/workspace/workspace_token.go @@ -32,12 +32,14 @@ func newTokenSelectionTableOut() *printutil.Table { } var ( - errInvalidWorkspaceTokenKey = errors.New("invalid Workspace API token selection") - ErrWorkspaceTokenNotFound = errors.New("no Workspace API token was found for the API token name you provided") + errInvalidWorkspaceTokenKey = errors.New("invalid Workspace API token selection") + errWorkspaceTokenInDeployment = errors.New("this Workspace API token has already been added to the Deployment with that role") + ErrWorkspaceTokenNotFound = errors.New("no Workspace API token was found for the API token name you provided") ) const ( - workspaceEntity = "WORKSPACE" + workspaceEntity = "WORKSPACE" + deploymentEntity = "DEPLOYMENT" ) // List all workspace Tokens @@ -154,6 +156,27 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. } } + for i := range token.Roles { + if token.Roles[i].EntityId == workspace { + if token.Roles[i].Role == role { + return errWorkspaceTokenInDeployment + } else { + continue + } + } + + if token.Roles[i].EntityId == ctx.Workspace { + workspaceRole = token.Roles[i].Role + } + + if token.Roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: token.Roles[i].EntityId, + Role: token.Roles[i].Role, + }) + } + } + apiTokenID := token.Id UpdateWorkspaceAPITokenRequest := astrocore.UpdateWorkspaceApiTokenJSONRequestBody{ @@ -465,3 +488,82 @@ func getWorkspaceTokenByID(id, workspaceID, orgID string, client astrocore.CoreC } return *resp.JSON200, nil } + +func AddWorkspaceTokenToDeployment(id, name, role, workspace string, deployment string, out io.Writer, client astrocore.CoreClient) error { + ctx, err := context.GetCurrentContext() + if err != nil { + return err + } + + organization := ctx.Organization + + if workspace == "" { + workspace = ctx.Workspace + } + + var token astrocore.ApiToken + if id == "" { + tokens, err := getWorkspaceTokens(workspace, client) + if err != nil { + return err + } + token, err = getWorkspaceToken(id, name, workspace, "\nPlease select the Workspace API token you would like to add to the Deployment:", tokens) + if err != nil { + return err + } + } else { + token, err = getWorkspaceTokenByID(id, workspace, organization, client) + if err != nil { + return err + } + } + + apiTokenID := token.Id + var workspaceRole string + apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: deployment, + Role: role, + } + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} + for i := range token.Roles { + if token.Roles[i].EntityId == deployment { + if token.Roles[i].Role == role { + return errWorkspaceTokenInDeployment + } else { + continue + } + } + + if token.Roles[i].EntityId == ctx.Workspace { + workspaceRole = token.Roles[i].Role + } + + if token.Roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: token.Roles[i].EntityId, + Role: token.Roles[i].Role, + }) + } + } + + updateWorkspaceAPITokenRoles := astrocore.UpdateWorkspaceApiTokenRolesRequest{ + Deployment: &apiTokenDeploymentRoles, + Workspace: &workspaceRole, + } + updateWorkspaceAPITokenRequest := astrocore.UpdateWorkspaceApiTokenRequest{ + Name: token.Name, + Description: token.Description, + Roles: &updateWorkspaceAPITokenRoles, + } + + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID, updateWorkspaceAPITokenRequest) + if err != nil { + return err + } + err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return err + } + fmt.Fprintf(out, "Astro Workspace API token %s was successfully added to the Deployment\n", token.Name) + return nil +} From 262926da934491f7ddcd49fb97465636b59445bb Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Fri, 29 Mar 2024 12:36:53 -0400 Subject: [PATCH 02/26] wip --- cmd/cloud/deployment.go | 83 +++++++++++++++++++++++++++++++++++++++++ cmd/cloud/workspace.go | 5 ++- 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/cmd/cloud/deployment.go b/cmd/cloud/deployment.go index 657c299ec..87297a63d 100644 --- a/cmd/cloud/deployment.go +++ b/cmd/cloud/deployment.go @@ -14,6 +14,7 @@ import ( "github.com/astronomer/astro-cli/cloud/organization" "github.com/astronomer/astro-cli/cloud/team" "github.com/astronomer/astro-cli/cloud/user" + "github.com/astronomer/astro-cli/cloud/workspace" "github.com/astronomer/astro-cli/pkg/httputil" "github.com/astronomer/astro-cli/pkg/input" "github.com/pkg/errors" @@ -936,6 +937,7 @@ func newDeploymentTokenRootCmd(out io.Writer) *cobra.Command { newDeploymentTokenUpdateCmd(out), newDeploymentTokenRotateCmd(out), newDeploymentTokenDeleteCmd(out), + newDeploymentTokenAddEntityTokenCmd(out), ) cmd.PersistentFlags().StringVar(&deploymentID, "deployment-id", "", "deployment where you would like to manage tokens") return cmd @@ -1029,6 +1031,87 @@ func newDeploymentTokenDeleteCmd(out io.Writer) *cobra.Command { return cmd } +//nolint:dupl +func newDeploymentTokenAddEntityTokenCmd(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "add", + Short: "Add a token to the deployment", + Long: "Add a token to the deployment", + } + cmd.SetOut(out) + cmd.AddCommand( + newDeploymentTokenAddWorkspaceToken(out), + newDeploymentTokenAddOrganizationToken(out), + ) + return cmd + +} +func newDeploymentTokenAddOrganizationToken(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "organization-token [ORG_TOKEN_ID]", + Short: "Add an Organization API token to an Astro Deployment", + Long: "Add an Organization API token to an Astro Deployment\n$astro deployment token add organization-token [ORG_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + RunE: func(cmd *cobra.Command, args []string) error { + return addOrgTokenToDeployment(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Deployment role to grant to the "+ + "Organization API token. Possible values are DEPLOYMENT_ADMIN or a custom role name.") + return cmd +} + +func newDeploymentTokenAddWorkspaceToken(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "workspace-token [WORKSPACE_TOKEN_ID]", + Short: "Add an Workspace API token to an Astro Deployment", + Long: "Add an Workspace API token to an Astro Deployment\n$astro deployment token add workspace-token [WORKSPACE_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + RunE: func(cmd *cobra.Command, args []string) error { + return addWorkspaceTokenToDeployment(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "workspace-token-name", "n", "", "The name of the WORKSPACE API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Deployment role to grant to the "+ + "Workspace API token. Possible values are DEPLOYMENT_ADMIN or a custom role name.") + return cmd +} + +func addOrgTokenToDeployment(cmd *cobra.Command, args []string, out io.Writer) error { + if deploymentID == "" { + return errors.New("flag --deployment-id is required") + } + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + orgTokenID = strings.ToLower(args[0]) + } + if tokenRole == "" { + // no role was provided so ask the user for it + tokenRole = input.Text("Enter a role for the new Deployment API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") + } + cmd.SilenceUsage = true + return organization.AddOrgTokenToDeployment(orgTokenID, orgTokenName, tokenRole, deploymentID, out, astroCoreClient) +} + +func addWorkspaceTokenToDeployment(cmd *cobra.Command, args []string, out io.Writer) error { + if deploymentID == "" { + return errors.New("flag --deployment-id is required") + } + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + workspaceTokenID = strings.ToLower(args[0]) + } + + if tokenRole == "" { + // no role was provided so ask the user for it + tokenRole = input.Text("Enter a role for the new Deployment API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") + } + + cmd.SilenceUsage = true + return workspace.AddWorkspaceTokenToDeployment(workspaceTokenID, orgTokenName, tokenRole, workspaceID, deploymentID, out, astroCoreClient) +} + func listDeploymentToken(cmd *cobra.Command, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") diff --git a/cmd/cloud/workspace.go b/cmd/cloud/workspace.go index 2d59e8927..b52f14263 100644 --- a/cmd/cloud/workspace.go +++ b/cmd/cloud/workspace.go @@ -32,6 +32,7 @@ var ( orgTokenName string tokenID string orgTokenID string + workspaceTokenID string cleanTokenOutput bool forceRotate bool tokenExpiration int @@ -230,7 +231,7 @@ func newWorkspaceTokenRootCmd(out io.Writer) *cobra.Command { newWorkspaceTokenUpdateCmd(out), newWorkspaceTokenRotateCmd(out), newWorkspaceTokenDeleteCmd(out), - newWorkspaceTokenAddCmd(out), + newWorkspaceTokenAddOrgTokenCmd(out), ) cmd.PersistentFlags().StringVar(&workspaceID, "workspace-id", "", "workspace where you would like to manage tokens") return cmd @@ -357,7 +358,7 @@ func newWorkspaceTokenDeleteCmd(out io.Writer) *cobra.Command { } //nolint:dupl -func newWorkspaceTokenAddCmd(out io.Writer) *cobra.Command { +func newWorkspaceTokenAddOrgTokenCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "add [ORG_TOKEN_ID]", Short: "Add an Organization API token to an Astro Workspace", From cf3924b6b0b346e15af093326f9ffb43b3551426 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Fri, 29 Mar 2024 12:37:57 -0400 Subject: [PATCH 03/26] wip --- cloud/workspace/workspace_token.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cloud/workspace/workspace_token.go b/cloud/workspace/workspace_token.go index ca6b911c2..795f91536 100644 --- a/cloud/workspace/workspace_token.go +++ b/cloud/workspace/workspace_token.go @@ -156,6 +156,8 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. } } + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} + for i := range token.Roles { if token.Roles[i].EntityId == workspace { if token.Roles[i].Role == role { @@ -165,10 +167,6 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. } } - if token.Roles[i].EntityId == ctx.Workspace { - workspaceRole = token.Roles[i].Role - } - if token.Roles[i].EntityType == deploymentEntity { apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ EntityId: token.Roles[i].EntityId, @@ -180,7 +178,9 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. apiTokenID := token.Id UpdateWorkspaceAPITokenRequest := astrocore.UpdateWorkspaceApiTokenJSONRequestBody{ - Roles: &astrocore.UpdateWorkspaceApiTokenRolesRequest{}, + Roles: &astrocore.UpdateWorkspaceApiTokenRolesRequest{ + Deployment: &apiTokenDeploymentRoles, + }, } if newName == "" { @@ -525,6 +525,7 @@ func AddWorkspaceTokenToDeployment(id, name, role, workspace string, deployment Role: role, } apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} + for i := range token.Roles { if token.Roles[i].EntityId == deployment { if token.Roles[i].Role == role { @@ -545,7 +546,6 @@ func AddWorkspaceTokenToDeployment(id, name, role, workspace string, deployment }) } } - updateWorkspaceAPITokenRoles := astrocore.UpdateWorkspaceApiTokenRolesRequest{ Deployment: &apiTokenDeploymentRoles, Workspace: &workspaceRole, From 422ca0713c273813754059e245054150d2129f45 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 2 Apr 2024 11:58:57 -0400 Subject: [PATCH 04/26] wip --- astro-client-iam-core/client.go | 30 ++- cloud/deployment/deployment_token.go | 228 ++++++++++++++++------ cloud/organization/organization_token.go | 230 +++++++++-------------- cloud/workspace/workspace_token.go | 163 +++++++--------- cmd/cloud/deployment.go | 123 +++++++++--- cmd/cloud/organization.go | 8 +- cmd/cloud/root.go | 5 +- cmd/cloud/root_test.go | 2 +- cmd/cloud/workspace.go | 8 +- cmd/root.go | 4 +- 10 files changed, 471 insertions(+), 330 deletions(-) diff --git a/astro-client-iam-core/client.go b/astro-client-iam-core/client.go index 760084b16..a405e5c78 100644 --- a/astro-client-iam-core/client.go +++ b/astro-client-iam-core/client.go @@ -2,14 +2,17 @@ package astroiamcore import ( "bytes" + httpContext "context" "encoding/json" "errors" "fmt" + "github.com/astronomer/astro-cli/context" + "github.com/astronomer/astro-cli/version" "net/http" + "net/url" + "runtime" "github.com/astronomer/astro-cli/pkg/httputil" - - astrocore "github.com/astronomer/astro-cli/astro-client-core" ) var ( @@ -24,7 +27,7 @@ type CoreClient = ClientWithResponsesInterface func NewIamCoreClient(c *httputil.HTTPClient) *ClientWithResponses { // we append base url in request editor, so set to an empty string here - cl, _ := NewClientWithResponses("", WithHTTPClient(c.HTTPClient), WithRequestEditorFn(astrocore.CoreRequestEditor)) + cl, _ := NewClientWithResponses("", WithHTTPClient(c.HTTPClient), WithRequestEditorFn(CoreRequestEditor)) return cl } @@ -39,3 +42,24 @@ func NormalizeAPIError(httpResp *http.Response, body []byte) error { } return nil } + +func CoreRequestEditor(ctx httpContext.Context, req *http.Request) error { + currentCtx, err := context.GetCurrentContext() + if err != nil { + return nil + } + os := runtime.GOOS + arch := runtime.GOARCH + baseURL := currentCtx.GetPublicRESTAPIURL("iam/v1beta1") + requestURL, err := url.Parse(baseURL + req.URL.String()) + if err != nil { + return fmt.Errorf("%w, %s", ErrorBaseURL, baseURL) + } + req.URL = requestURL + req.Header.Add("authorization", currentCtx.Token) + req.Header.Add("x-astro-client-identifier", "cli") + req.Header.Add("x-astro-client-version", version.CurrVersion) + req.Header.Add("x-client-os-identifier", os+"-"+arch) + req.Header.Add("User-Agent", fmt.Sprintf("astro-cli/%s", version.CurrVersion)) + return nil +} diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index 3ca06eb3e..045b8520e 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -4,6 +4,7 @@ import ( httpContext "context" "errors" "fmt" + astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" "io" "os" "strconv" @@ -37,6 +38,7 @@ var ( const ( deploymentEntity = "DEPLOYMENT" + workspaceEntity = "WORKSPACE" ) // List all deployment Tokens @@ -112,28 +114,18 @@ func CreateToken(name, description, role, deployment string, expiration int, cle } // Update a deployment token -func UpdateToken(id, name, newName, description, role, deployment string, out io.Writer, client astrocore.CoreClient) error { +func UpdateToken(id, name, newName, description, role, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - var token astrocore.ApiToken - if id == "" { - tokens, err := getDeploymentTokens(deployment, client) - if err != nil { - return err - } - token, err = getDeploymentToken(id, name, deployment, "\nPlease select the Deployment API token you would like to update:", tokens) - if err != nil { - return err - } - } else { - token, err = getDeploymentTokenByID(id, deployment, ctx.Organization, client) - if err != nil { - return err - } + organization := ctx.Organization + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + if err != nil { + return err } + roles := *token.Roles apiTokenID := token.Id @@ -152,9 +144,9 @@ func UpdateToken(id, name, newName, description, role, deployment string, out io } if role == "" { - for i := range token.Roles { - if token.Roles[i].EntityType == deploymentEntity && token.Roles[i].EntityId == deployment { - role = token.Roles[i].Role + for i := range roles { + if roles[i].EntityType == deploymentEntity && roles[i].EntityId == deployment { + role = roles[i].Role } } UpdateDeploymentAPITokenRequest.Role = role @@ -175,27 +167,16 @@ func UpdateToken(id, name, newName, description, role, deployment string, out io } // rotate a deployment API token -func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient) error { +func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - var token astrocore.ApiToken - if id == "" { - tokens, err := getDeploymentTokens(deployment, client) - if err != nil { - return err - } - token, err = getDeploymentToken(id, name, deployment, "\nPlease select the Deployment API token you would like to update:", tokens) - if err != nil { - return err - } - } else { - token, err = getDeploymentTokenByID(id, deployment, ctx.Organization, client) - if err != nil { - return err - } + organization := ctx.Organization + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + if err != nil { + return err } apiTokenID := token.Id @@ -230,27 +211,16 @@ func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Wr } // delete a deployments api token -func DeleteToken(id, name, deployment string, force bool, out io.Writer, client astrocore.CoreClient) error { +func DeleteToken(id, name, deployment string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - var token astrocore.ApiToken - if id == "" { - tokens, err := getDeploymentTokens(deployment, client) - if err != nil { - return err - } - token, err = getDeploymentToken(id, name, deployment, "\nPlease select the Deployment API token you would like to update:", tokens) - if err != nil { - return err - } - } else { - token, err = getDeploymentTokenByID(id, deployment, ctx.Organization, client) - if err != nil { - return err - } + organization := ctx.Organization + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + if err != nil { + return err } apiTokenID := token.Id if !force { @@ -403,14 +373,160 @@ func TimeAgo(date time.Time) string { } } -func getDeploymentTokenByID(id, deploymentID, orgID string, client astrocore.CoreClient) (token astrocore.ApiToken, err error) { - resp, err := client.GetDeploymentApiTokenWithResponse(httpContext.Background(), orgID, deploymentID, id) +func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { + resp, err := client.GetApiTokenWithResponse(httpContext.Background(), orgID, id) if err != nil { - return astrocore.ApiToken{}, err + return astrocoreiam.ApiToken{}, err } - err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + err = astrocoreiam.NormalizeAPIError(resp.HTTPResponse, resp.Body) if err != nil { - return astrocore.ApiToken{}, err + return astrocoreiam.ApiToken{}, err } return *resp.JSON200, nil } + +func GetDeploymentTokenFromInputOrUser(id, name, deployment, organization string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { + if id == "" { + tokens, err := getDeploymentTokens(deployment, client) + if err != nil { + return token, err + } + tokenFromList, err := getDeploymentToken(id, name, deployment, "\nPlease select the Organization API token you would like to remove from the Deployment:", tokens) + + if err != nil { + return token, err + } + token, err = getTokenByID(tokenFromList.Id, organization, iamClient) + if err != nil { + return token, err + } + } else { + token, err = getTokenByID(id, organization, iamClient) + if err != nil { + return token, err + } + } + return token, err +} + +func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { + ctx, err := context.GetCurrentContext() + if err != nil { + return err + } + organization := ctx.Organization + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + if err != nil { + return err + } + roles := *token.Roles + + apiTokenID := token.Id + var orgRole string + apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} + for i := range roles { + if roles[i].EntityId == deployment { + continue // this removes the role in question + } + + if roles[i].EntityId == ctx.Organization { + orgRole = roles[i].Role + } + + if roles[i].EntityType == workspaceEntity { + apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + + if roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + } + + updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ + Organization: orgRole, + Deployment: &apiTokenDeploymentRoles, + Workspace: &apiTokenWorkspaceRoles, + } + updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ + Name: token.Name, + Description: token.Description, + Roles: updateOrganizationAPITokenRoles, + } + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) + if err != nil { + return err + } + err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return err + } + fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) + return nil +} + +func RemoveWorkspaceTokenDeploymentRole(id, name, workspace string, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { + ctx, err := context.GetCurrentContext() + if err != nil { + return err + } + + organization := ctx.Organization + + if workspace == "" { + workspace = ctx.Workspace + } + + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + if err != nil { + return err + } + roles := *token.Roles + + apiTokenID := token.Id + var workspaceRole string + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} + + for i := range roles { + if roles[i].EntityId == deployment { + continue // this removes the role in question + } + + if roles[i].EntityId == ctx.Workspace { + workspaceRole = roles[i].Role + } + + if roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + } + updateWorkspaceAPITokenRoles := astrocore.UpdateWorkspaceApiTokenRolesRequest{ + Deployment: &apiTokenDeploymentRoles, + Workspace: &workspaceRole, + } + updateWorkspaceAPITokenRequest := astrocore.UpdateWorkspaceApiTokenRequest{ + Name: token.Name, + Description: token.Description, + Roles: &updateWorkspaceAPITokenRoles, + } + + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID, updateWorkspaceAPITokenRequest) + if err != nil { + return err + } + err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return err + } + fmt.Fprintf(out, "Astro Workspace API token %s was successfully added to the Deployment\n", token.Name) + return nil +} diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index d8aeb7826..68b495286 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -4,6 +4,7 @@ import ( httpContext "context" "errors" "fmt" + astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" "io" "os" "strconv" @@ -52,7 +53,7 @@ func newTokenSelectionTableOut() *printutil.Table { } } -func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, client astrocore.CoreClient) error { +func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { err := user.IsWorkspaceRoleValid(role) if err != nil { return err @@ -64,23 +65,10 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli if workspace == "" { workspace = ctx.Workspace } - var token astrocore.ApiToken - if id == "" { - tokens, err := getOrganizationTokens(client) - if err != nil { - return err - } - token, err = getOrganizationToken(id, name, "\nPlease select the Organization API token you would like to add to the Workspace:", tokens) - if err != nil { - return err - } - } else { - token, err = getOrganizationTokenByID(id, ctx.Organization, client) - if err != nil { - return err - } + token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) + if err != nil { + return err } - apiTokenID := token.Id var orgRole string apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} @@ -89,30 +77,30 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli Role: role, } apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} - - for i := range token.Roles { - if token.Roles[i].EntityId == workspace { - if token.Roles[i].Role == role { + roles := *token.Roles + for i := range roles { + if roles[i].EntityId == workspace { + if roles[i].Role == role { return errOrgTokenInWorkspace } else { continue } } - if token.Roles[i].EntityId == ctx.Organization { - orgRole = token.Roles[i].Role + if roles[i].EntityId == ctx.Organization { + orgRole = roles[i].Role } - if token.Roles[i].EntityType == deploymentEntity { + if roles[i].EntityType == deploymentEntity { apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: token.Roles[i].EntityId, - Role: token.Roles[i].Role, + EntityId: roles[i].EntityId, + Role: roles[i].Role, }) } - if token.Roles[i].EntityType == workspaceEntity { + if roles[i].EntityType == workspaceEntity { apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: token.Roles[i].EntityId, - Role: token.Roles[i].Role, + EntityId: roles[i].EntityId, + Role: roles[i].Role, }) } } @@ -140,29 +128,16 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli return nil } -func AddOrgTokenToDeployment(id, name, role, deployment string, out io.Writer, client astrocore.CoreClient) error { +func UpsertOrgTokenDeploymentRole(id, name, role, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - var token astrocore.ApiToken - if id == "" { - tokens, err := getOrganizationTokens(client) - if err != nil { - return err - } - token, err = getOrganizationToken(id, name, "\nPlease select the Organization API token you would like to add to the Deployment:", tokens) - if err != nil { - return err - } - } else { - token, err = getOrganizationTokenByID(id, ctx.Organization, client) - if err != nil { - return err - } + token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) + if err != nil { + return err } - apiTokenID := token.Id var orgRole string apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} @@ -171,31 +146,31 @@ func AddOrgTokenToDeployment(id, name, role, deployment string, out io.Writer, c Role: role, } apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} - - for i := range token.Roles { - if token.Roles[i].EntityId == deployment { - if token.Roles[i].Role == role { + roles := *token.Roles + for i := range roles { + if roles[i].EntityId == deployment { + if roles[i].Role == role { return errOrgTokenInDeployment } else { continue } } - if token.Roles[i].EntityId == ctx.Organization { - orgRole = token.Roles[i].Role + if roles[i].EntityId == ctx.Organization { + orgRole = roles[i].Role } - if token.Roles[i].EntityType == workspaceEntity { + if roles[i].EntityType == workspaceEntity { apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: token.Roles[i].EntityId, - Role: token.Roles[i].Role, + EntityId: roles[i].EntityId, + Role: roles[i].Role, }) } - if token.Roles[i].EntityType == deploymentEntity { + if roles[i].EntityType == deploymentEntity { apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: token.Roles[i].EntityId, - Role: token.Roles[i].Role, + EntityId: roles[i].EntityId, + Role: roles[i].Role, }) } } @@ -278,18 +253,6 @@ func getOrganizationTokens(client astrocore.CoreClient) ([]astrocore.ApiToken, e return APITokens, nil } -func getOrganizationTokenByID(id, orgID string, client astrocore.CoreClient) (token astrocore.ApiToken, err error) { - resp, err := client.GetOrganizationApiTokenWithResponse(httpContext.Background(), orgID, id) - if err != nil { - return astrocore.ApiToken{}, err - } - err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) - if err != nil { - return astrocore.ApiToken{}, err - } - return *resp.JSON200, nil -} - func getOrganizationToken(id, name, message string, tokens []astrocore.ApiToken) (token astrocore.ApiToken, err error) { //nolint:gocognit switch { case id == "" && name == "": @@ -370,31 +333,52 @@ func ListTokens(client astrocore.CoreClient, out io.Writer) error { return nil } -// List all roles for a given organization Token -func ListTokenRoles(id string, client astrocore.CoreClient, out io.Writer) (err error) { - var apiToken astrocore.ApiToken +func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { + resp, err := client.GetApiTokenWithResponse(httpContext.Background(), orgID, id) + if err != nil { + return astrocoreiam.ApiToken{}, err + } + err = astrocoreiam.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return astrocoreiam.ApiToken{}, err + } + return *resp.JSON200, nil +} + +func GetTokenFromInputOrUser(id, name, organization string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { if id == "" { tokens, err := getOrganizationTokens(client) if err != nil { - return err + return token, err } - apiToken, err = getOrganizationToken(id, "", "\nPlease select the Organization API token you would like to update:", tokens) + tokenFromList, err := getOrganizationToken(id, name, "\nPlease select the Organization API token you would like to update:", tokens) + if err != nil { - return err + return token, err } - } else { - ctx, err := context.GetCurrentContext() + token, err = getTokenByID(tokenFromList.Id, organization, iamClient) if err != nil { - return err + return token, err } - apiToken, err = getOrganizationTokenByID(id, ctx.Organization, client) + } else { + token, err = getTokenByID(id, organization, iamClient) if err != nil { - return err + return token, err } } + return token, err +} + +// List all roles for a given organization Token +func ListTokenRoles(id string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient, out io.Writer) (err error) { + ctx, err := context.GetCurrentContext() + apiToken, err := GetTokenFromInputOrUser(id, "", ctx.Organization, client, iamClient) + if err != nil { + return err + } tab := newTokenRolesTableOut() - for _, tokenRole := range apiToken.Roles { + for _, tokenRole := range *apiToken.Roles { role := tokenRole.Role entityID := tokenRole.EntityId entityType := string(tokenRole.EntityType) @@ -447,28 +431,15 @@ func CreateToken(name, description, role string, expiration int, cleanOutput boo } // Update a organization token -func UpdateToken(id, name, newName, description, role string, out io.Writer, client astrocore.CoreClient) error { +func UpdateToken(id, name, newName, description, role string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - var token astrocore.ApiToken - if id == "" { - tokens, err := getOrganizationTokens(client) - if err != nil { - return err - } - token, err = getOrganizationToken(id, name, "\nPlease select the Organization API token you would like to update:", tokens) - if err != nil { - return err - } - } else { - token, err = getOrganizationTokenByID(id, ctx.Organization, client) - if err != nil { - return err - } + token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) + if err != nil { + return err } - apiTokenID := token.Id UpdateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenJSONRequestBody{} @@ -488,24 +459,24 @@ func UpdateToken(id, name, newName, description, role string, out io.Writer, cli var currentOrgRole string apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} - - for i := range token.Roles { - if token.Roles[i].EntityType == workspaceEntity { + roles := *token.Roles + for i := range roles { + if roles[i].EntityType == workspaceEntity { apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: token.Roles[i].EntityId, - Role: token.Roles[i].Role, + EntityId: roles[i].EntityId, + Role: roles[i].Role, }) } - if token.Roles[i].EntityType == deploymentEntity { + if roles[i].EntityType == deploymentEntity { apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: token.Roles[i].EntityId, - Role: token.Roles[i].Role, + EntityId: roles[i].EntityId, + Role: roles[i].Role, }) } - if token.Roles[i].EntityType == organizationEntity { - currentOrgRole = token.Roles[i].Role + if roles[i].EntityType == organizationEntity { + currentOrgRole = roles[i].Role } } if role == "" { @@ -542,27 +513,14 @@ func UpdateToken(id, name, newName, description, role string, out io.Writer, cli } // rotate a organization API token -func RotateToken(id, name string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient) error { +func RotateToken(id, name string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - var token astrocore.ApiToken - - if id == "" { - tokens, err := getOrganizationTokens(client) - if err != nil { - return err - } - token, err = getOrganizationToken(id, name, "\nPlease select the Organization API token you would like to rotate:", tokens) - if err != nil { - return err - } - } else { - token, err = getOrganizationTokenByID(id, ctx.Organization, client) - if err != nil { - return err - } + token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) + if err != nil { + return err } apiTokenID := token.Id @@ -597,26 +555,14 @@ func RotateToken(id, name string, cleanOutput, force bool, out io.Writer, client } // delete a organizations api token -func DeleteToken(id, name string, force bool, out io.Writer, client astrocore.CoreClient) error { +func DeleteToken(id, name string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - var token astrocore.ApiToken - if id == "" { - tokens, err := getOrganizationTokens(client) - if err != nil { - return err - } - token, err = getOrganizationToken(id, name, "\nPlease select the Organization API token you would like to delete:", tokens) - if err != nil { - return err - } - } else { - token, err = getOrganizationTokenByID(id, ctx.Organization, client) - if err != nil { - return err - } + token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) + if err != nil { + return err } apiTokenID := token.Id if string(token.Type) == organizationEntity { diff --git a/cloud/workspace/workspace_token.go b/cloud/workspace/workspace_token.go index 795f91536..6e81d66be 100644 --- a/cloud/workspace/workspace_token.go +++ b/cloud/workspace/workspace_token.go @@ -10,6 +10,7 @@ import ( "time" astrocore "github.com/astronomer/astro-cli/astro-client-core" + astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" "github.com/astronomer/astro-cli/cloud/user" "github.com/astronomer/astro-cli/context" "github.com/astronomer/astro-cli/pkg/ansi" @@ -130,7 +131,7 @@ func CreateToken(name, description, role, workspace string, expiration int, clea } // Update a workspace token -func UpdateToken(id, name, newName, description, role, workspace string, out io.Writer, client astrocore.CoreClient) error { +func UpdateToken(id, name, newName, description, role, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -139,38 +140,27 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. workspace = ctx.Workspace } - var token astrocore.ApiToken - if id == "" { - tokens, err := getWorkspaceTokens(workspace, client) - if err != nil { - return err - } - token, err = getWorkspaceToken(id, name, workspace, "\nPlease select the Workspace API token you would like to update:", tokens) - if err != nil { - return err - } - } else { - token, err = getWorkspaceTokenByID(id, workspace, ctx.Organization, client) - if err != nil { - return err - } - } + organization := ctx.Organization + token, err := GetTokenFromInputOrUser(id, name, workspace, organization, client, iamClient) + if err != nil { + return err + } apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} - - for i := range token.Roles { - if token.Roles[i].EntityId == workspace { - if token.Roles[i].Role == role { + roles := *token.Roles + for i := range roles { + if roles[i].EntityId == workspace { + if roles[i].Role == role { return errWorkspaceTokenInDeployment } else { continue } } - if token.Roles[i].EntityType == deploymentEntity { + if roles[i].EntityType == deploymentEntity { apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: token.Roles[i].EntityId, - Role: token.Roles[i].Role, + EntityId: roles[i].EntityId, + Role: roles[i].Role, }) } } @@ -196,9 +186,9 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. } if role == "" { - for i := range token.Roles { - if token.Roles[i].EntityType == workspaceEntity && token.Roles[i].EntityId == workspace { - role = token.Roles[i].Role + for i := range roles { + if roles[i].EntityType == workspaceEntity && roles[i].EntityId == workspace { + role = roles[i].Role } } err := user.IsWorkspaceRoleValid(role) @@ -214,7 +204,7 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. UpdateWorkspaceAPITokenRequest.Roles.Workspace = &role } - resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), ctx.Organization, workspace, apiTokenID, UpdateWorkspaceAPITokenRequest) + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID, UpdateWorkspaceAPITokenRequest) if err != nil { return err } @@ -227,7 +217,7 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. } // rotate a workspace API token -func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient) error { +func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -235,21 +225,10 @@ func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Wri if workspace == "" { workspace = ctx.Workspace } - var token astrocore.ApiToken - if id == "" { - tokens, err := getWorkspaceTokens(workspace, client) - if err != nil { - return err - } - token, err = getWorkspaceToken(id, name, workspace, "\nPlease select the Workspace API token you would like to update:", tokens) - if err != nil { - return err - } - } else { - token, err = getWorkspaceTokenByID(id, workspace, ctx.Organization, client) - if err != nil { - return err - } + organization := ctx.Organization + token, err := GetTokenFromInputOrUser(id, name, workspace, organization, client, iamClient) + if err != nil { + return err } apiTokenID := token.Id @@ -263,7 +242,7 @@ func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Wri return nil } } - resp, err := client.RotateWorkspaceApiTokenWithResponse(httpContext.Background(), ctx.Organization, workspace, apiTokenID) + resp, err := client.RotateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID) if err != nil { return err } @@ -284,7 +263,7 @@ func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Wri } // delete a workspaces api token -func DeleteToken(id, name, workspace string, force bool, out io.Writer, client astrocore.CoreClient) error { +func DeleteToken(id, name, workspace string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -292,21 +271,10 @@ func DeleteToken(id, name, workspace string, force bool, out io.Writer, client a if workspace == "" { workspace = ctx.Workspace } - var token astrocore.ApiToken - if id == "" { - tokens, err := getWorkspaceTokens(workspace, client) - if err != nil { - return err - } - token, err = getWorkspaceToken(id, name, workspace, "\nPlease select the Workspace API token you would like to update:", tokens) - if err != nil { - return err - } - } else { - token, err = getWorkspaceTokenByID(id, workspace, ctx.Organization, client) - if err != nil { - return err - } + organization := ctx.Organization + token, err := GetTokenFromInputOrUser(id, name, workspace, organization, client, iamClient) + if err != nil { + return err } apiTokenID := token.Id if string(token.Type) == workspaceEntity { @@ -332,7 +300,7 @@ func DeleteToken(id, name, workspace string, force bool, out io.Writer, client a } } - resp, err := client.DeleteWorkspaceApiTokenWithResponse(httpContext.Background(), ctx.Organization, workspace, apiTokenID) + resp, err := client.DeleteWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID) if err != nil { return err } @@ -477,19 +445,42 @@ func TimeAgo(date time.Time) string { } } -func getWorkspaceTokenByID(id, workspaceID, orgID string, client astrocore.CoreClient) (token astrocore.ApiToken, err error) { - resp, err := client.GetWorkspaceApiTokenWithResponse(httpContext.Background(), orgID, workspaceID, id) +func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { + resp, err := client.GetApiTokenWithResponse(httpContext.Background(), orgID, id) if err != nil { - return astrocore.ApiToken{}, err + return astrocoreiam.ApiToken{}, err } - err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + err = astrocoreiam.NormalizeAPIError(resp.HTTPResponse, resp.Body) if err != nil { - return astrocore.ApiToken{}, err + return astrocoreiam.ApiToken{}, err } return *resp.JSON200, nil } -func AddWorkspaceTokenToDeployment(id, name, role, workspace string, deployment string, out io.Writer, client astrocore.CoreClient) error { +func GetTokenFromInputOrUser(id, name, workspace, organization string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { + if id == "" { + tokens, err := getWorkspaceTokens(workspace, client) + if err != nil { + return token, err + } + tokenFromList, err := getWorkspaceToken(id, name, workspace, "\nPlease select the Workspace API token you would like to add to the Deployment:", tokens) + if err != nil { + return token, err + } + token, err = getTokenByID(tokenFromList.Id, organization, iamClient) + if err != nil { + return token, err + } + } else { + token, err = getTokenByID(id, organization, iamClient) + if err != nil { + return token, err + } + } + return token, err +} + +func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace string, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -501,23 +492,10 @@ func AddWorkspaceTokenToDeployment(id, name, role, workspace string, deployment workspace = ctx.Workspace } - var token astrocore.ApiToken - if id == "" { - tokens, err := getWorkspaceTokens(workspace, client) - if err != nil { - return err - } - token, err = getWorkspaceToken(id, name, workspace, "\nPlease select the Workspace API token you would like to add to the Deployment:", tokens) - if err != nil { - return err - } - } else { - token, err = getWorkspaceTokenByID(id, workspace, organization, client) - if err != nil { - return err - } + token, err := GetTokenFromInputOrUser(id, name, workspace, organization, client, iamClient) + if err != nil { + return err } - apiTokenID := token.Id var workspaceRole string apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ @@ -526,23 +504,24 @@ func AddWorkspaceTokenToDeployment(id, name, role, workspace string, deployment } apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} - for i := range token.Roles { - if token.Roles[i].EntityId == deployment { - if token.Roles[i].Role == role { + for i := range *token.Roles { + roles := *token.Roles + if roles[i].EntityId == deployment { + if roles[i].Role == role { return errWorkspaceTokenInDeployment } else { continue } } - if token.Roles[i].EntityId == ctx.Workspace { - workspaceRole = token.Roles[i].Role + if roles[i].EntityId == ctx.Workspace { + workspaceRole = roles[i].Role } - if token.Roles[i].EntityType == deploymentEntity { + if roles[i].EntityType == deploymentEntity { apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: token.Roles[i].EntityId, - Role: token.Roles[i].Role, + EntityId: roles[i].EntityId, + Role: roles[i].Role, }) } } diff --git a/cmd/cloud/deployment.go b/cmd/cloud/deployment.go index 87297a63d..c921dbbf3 100644 --- a/cmd/cloud/deployment.go +++ b/cmd/cloud/deployment.go @@ -937,7 +937,8 @@ func newDeploymentTokenRootCmd(out io.Writer) *cobra.Command { newDeploymentTokenUpdateCmd(out), newDeploymentTokenRotateCmd(out), newDeploymentTokenDeleteCmd(out), - newDeploymentTokenAddEntityTokenCmd(out), + newWorkspaceTokenManageCmd(out), + newOrgTokenManageCmd(out), ) cmd.PersistentFlags().StringVar(&deploymentID, "deployment-id", "", "deployment where you would like to manage tokens") return cmd @@ -982,8 +983,8 @@ func newDeploymentTokenUpdateCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "update [TOKEN_ID]", Aliases: []string{"up"}, - Short: "Update a Deployment or Organaization API token", - Long: "Update a Deployment or Organaization API token that has a role in an Astro Deployment\n$astro workspace token update [TOKEN_ID] --name [new token name] --role [Possible values are DEPLOYMENT_ADMIN or a custom role name].", + Short: "Update a Deployment API token", + Long: "Update a Deployment API token that has a role in an Astro Deployment\n$astro workspace token update [TOKEN_ID] --name [new token name] --role [Possible values are DEPLOYMENT_ADMIN or a custom role name].", RunE: func(cmd *cobra.Command, args []string) error { return updateDeploymentToken(cmd, args, out) }, @@ -1032,27 +1033,42 @@ func newDeploymentTokenDeleteCmd(out io.Writer) *cobra.Command { } //nolint:dupl -func newDeploymentTokenAddEntityTokenCmd(out io.Writer) *cobra.Command { +func newOrgTokenManageCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "add", - Short: "Add a token to the deployment", - Long: "Add a token to the deployment", + Use: "organization-token", + Short: "Manage organization tokens in a deployment", + Long: "Manage organization tokens in a deployment", } cmd.SetOut(out) cmd.AddCommand( - newDeploymentTokenAddWorkspaceToken(out), - newDeploymentTokenAddOrganizationToken(out), + newUpsertOrganizationTokenDeploymentRole(out), + newRemoveOrganizationTokenDeploymentRole(out), ) return cmd +} +//nolint:dupl +func newWorkspaceTokenManageCmd(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "workspace-token", + Short: "Manage workspace tokens in a deployment", + Long: "Manage workspace tokens in a deployment", + } + cmd.SetOut(out) + cmd.AddCommand( + newUpsertWorkspaceTokenDeploymentRole(out), + newRemoveWorkspaceTokenDeploymentRole(out), + ) + return cmd } -func newDeploymentTokenAddOrganizationToken(out io.Writer) *cobra.Command { + +func newUpsertOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "organization-token [ORG_TOKEN_ID]", - Short: "Add an Organization API token to an Astro Deployment", - Long: "Add an Organization API token to an Astro Deployment\n$astro deployment token add organization-token [ORG_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + Use: "upsert [ORG_TOKEN_ID]", + Short: "Upsert an Organization API token's Deployment Role", + Long: "Upsert an Organization API token's Deployment Role\n$astro deployment token organization-token upsert [ORG_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", RunE: func(cmd *cobra.Command, args []string) error { - return addOrgTokenToDeployment(cmd, args, out) + return upsertOrgTokenToDeploymentRole(cmd, args, out) }, } cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") @@ -1061,13 +1077,13 @@ func newDeploymentTokenAddOrganizationToken(out io.Writer) *cobra.Command { return cmd } -func newDeploymentTokenAddWorkspaceToken(out io.Writer) *cobra.Command { +func newUpsertWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "workspace-token [WORKSPACE_TOKEN_ID]", - Short: "Add an Workspace API token to an Astro Deployment", - Long: "Add an Workspace API token to an Astro Deployment\n$astro deployment token add workspace-token [WORKSPACE_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + Use: "upsert [WORKSPACE_TOKEN_ID]", + Short: "Upsert a Workspace API token's Deployment Role", + Long: "Upsert a Workspace API token's Deployment Role\n$astro deployment token workspace-token upsert [WORKSPACE_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", RunE: func(cmd *cobra.Command, args []string) error { - return addWorkspaceTokenToDeployment(cmd, args, out) + return upsertWorkspaceTokenDeploymentRole(cmd, args, out) }, } cmd.Flags().StringVarP(&orgTokenName, "workspace-token-name", "n", "", "The name of the WORKSPACE API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") @@ -1076,7 +1092,7 @@ func newDeploymentTokenAddWorkspaceToken(out io.Writer) *cobra.Command { return cmd } -func addOrgTokenToDeployment(cmd *cobra.Command, args []string, out io.Writer) error { +func upsertOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } @@ -1090,10 +1106,11 @@ func addOrgTokenToDeployment(cmd *cobra.Command, args []string, out io.Writer) e tokenRole = input.Text("Enter a role for the new Deployment API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") } cmd.SilenceUsage = true - return organization.AddOrgTokenToDeployment(orgTokenID, orgTokenName, tokenRole, deploymentID, out, astroCoreClient) + + return organization.UpsertOrgTokenDeploymentRole(orgTokenID, orgTokenName, tokenRole, deploymentID, out, astroCoreClient, astroCoreIamClient) } -func addWorkspaceTokenToDeployment(cmd *cobra.Command, args []string, out io.Writer) error { +func upsertWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } @@ -1109,7 +1126,61 @@ func addWorkspaceTokenToDeployment(cmd *cobra.Command, args []string, out io.Wri } cmd.SilenceUsage = true - return workspace.AddWorkspaceTokenToDeployment(workspaceTokenID, orgTokenName, tokenRole, workspaceID, deploymentID, out, astroCoreClient) + return workspace.UpsertWorkspaceTokenDeploymentRole(workspaceTokenID, orgTokenName, tokenRole, workspaceID, deploymentID, out, astroCoreClient, astroCoreIamClient) +} + +func newRemoveOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "remove [ORG_TOKEN_ID]", + Short: "Remove an Organization API token's Deployment Role", + Long: "Remove an Organization API token's Deployment Role\n$astro deployment token organization-token remove [ORG_TOKEN_ID] --name [token name].", + RunE: func(cmd *cobra.Command, args []string) error { + return removeOrgTokenFromDeploymentRole(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to remove from a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") + return cmd +} + +func newRemoveWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "remove [WORKSPACE_TOKEN_ID]", + Short: "Remove a Workspace API token's Deployment Role", + Long: "Remove a Workspace API token's Deployment Role\n$astro deployment token workspace-token remove [WORKSPACE_TOKEN_ID] --name [token name].", + RunE: func(cmd *cobra.Command, args []string) error { + return removeWorkspaceTokenDeploymentRole(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "workspace-token-name", "n", "", "The name of the WORKSPACE API token you want to remove from a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") + return cmd +} + +func removeOrgTokenFromDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { + if deploymentID == "" { + return errors.New("flag --deployment-id is required") + } + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + orgTokenID = strings.ToLower(args[0]) + } + + cmd.SilenceUsage = true + return deployment.RemoveOrgTokenDeploymentRole(orgTokenID, orgTokenName, deploymentID, out, astroCoreClient, astroCoreIamClient) +} + +func removeWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { + if deploymentID == "" { + return errors.New("flag --deployment-id is required") + } + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + workspaceTokenID = strings.ToLower(args[0]) + } + + cmd.SilenceUsage = true + return deployment.RemoveWorkspaceTokenDeploymentRole(workspaceTokenID, orgTokenName, workspaceID, deploymentID, out, astroCoreClient, astroCoreIamClient) } func listDeploymentToken(cmd *cobra.Command, out io.Writer) error { @@ -1149,7 +1220,7 @@ func updateDeploymentToken(cmd *cobra.Command, args []string, out io.Writer) err } cmd.SilenceUsage = true - return deployment.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, deploymentID, out, astroCoreClient) + return deployment.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, deploymentID, out, astroCoreClient, astroCoreIamClient) } func rotateDeploymentToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -1162,7 +1233,7 @@ func rotateDeploymentToken(cmd *cobra.Command, args []string, out io.Writer) err tokenID = strings.ToLower(args[0]) } cmd.SilenceUsage = true - return deployment.RotateToken(tokenID, name, deploymentID, cleanTokenOutput, forceRotate, out, astroCoreClient) + return deployment.RotateToken(tokenID, name, deploymentID, cleanTokenOutput, forceRotate, out, astroCoreClient, astroCoreIamClient) } func deleteDeploymentToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -1176,7 +1247,7 @@ func deleteDeploymentToken(cmd *cobra.Command, args []string, out io.Writer) err } cmd.SilenceUsage = true - return deployment.DeleteToken(tokenID, name, deploymentID, forceDelete, out, astroCoreClient) + return deployment.DeleteToken(tokenID, name, deploymentID, forceDelete, out, astroCoreClient, astroCoreIamClient) } func getOverrideUntil(until, forDuration string) (*time.Time, error) { diff --git a/cmd/cloud/organization.go b/cmd/cloud/organization.go index 3d45d08ad..c383e1246 100644 --- a/cmd/cloud/organization.go +++ b/cmd/cloud/organization.go @@ -584,7 +584,7 @@ func listOrganizationTokenRoles(cmd *cobra.Command, args []string, out io.Writer tokenID = strings.ToLower(args[0]) } cmd.SilenceUsage = true - return organization.ListTokenRoles(tokenID, astroCoreClient, out) + return organization.ListTokenRoles(tokenID, astroCoreClient, astroCoreIamClient, out) } //nolint:dupl @@ -616,7 +616,7 @@ func updateOrganizationToken(cmd *cobra.Command, args []string, out io.Writer) e } cmd.SilenceUsage = true - return organization.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, out, astroCoreClient) + return organization.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, out, astroCoreClient, astroCoreIamClient) } //nolint:dupl @@ -628,7 +628,7 @@ func rotateOrganizationToken(cmd *cobra.Command, args []string, out io.Writer) e } cmd.SilenceUsage = true - return organization.RotateToken(tokenID, name, cleanTokenOutput, forceRotate, out, astroCoreClient) + return organization.RotateToken(tokenID, name, cleanTokenOutput, forceRotate, out, astroCoreClient, astroCoreIamClient) } //nolint:dupl @@ -640,7 +640,7 @@ func deleteOrganizationToken(cmd *cobra.Command, args []string, out io.Writer) e } cmd.SilenceUsage = true - return organization.DeleteToken(tokenID, name, forceDelete, out, astroCoreClient) + return organization.DeleteToken(tokenID, name, forceDelete, out, astroCoreClient, astroCoreIamClient) } //nolint:dupl diff --git a/cmd/cloud/root.go b/cmd/cloud/root.go index 9368c5904..cbf752359 100644 --- a/cmd/cloud/root.go +++ b/cmd/cloud/root.go @@ -5,20 +5,23 @@ import ( airflow "github.com/astronomer/astro-cli/airflow-client" astrocore "github.com/astronomer/astro-cli/astro-client-core" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" astroplatformcore "github.com/astronomer/astro-cli/astro-client-platform-core" "github.com/spf13/cobra" ) var ( astroCoreClient astrocore.CoreClient + astroCoreIamClient astroiamcore.CoreClient platformCoreClient astroplatformcore.CoreClient airflowAPIClient airflow.Client ) // AddCmds adds all the command initialized in this package for the cmd package to import -func AddCmds(astroPlatformCoreClient astroplatformcore.CoreClient, coreClient astrocore.CoreClient, airflowClient airflow.Client, out io.Writer) []*cobra.Command { +func AddCmds(astroPlatformCoreClient astroplatformcore.CoreClient, coreClient astrocore.CoreClient, airflowClient airflow.Client, iamCoreClient astroiamcore.CoreClient, out io.Writer) []*cobra.Command { astroCoreClient = coreClient platformCoreClient = astroPlatformCoreClient + astroCoreIamClient = iamCoreClient airflowAPIClient = airflowClient return []*cobra.Command{ NewDeployCmd(), diff --git a/cmd/cloud/root_test.go b/cmd/cloud/root_test.go index fba2b7985..84b3ef573 100644 --- a/cmd/cloud/root_test.go +++ b/cmd/cloud/root_test.go @@ -9,7 +9,7 @@ import ( func TestAddCmds(t *testing.T) { buf := new(bytes.Buffer) - cmds := AddCmds(nil, nil, nil, buf) + cmds := AddCmds(nil, nil, nil, nil, buf) for cmdIdx := range cmds { assert.Contains(t, []string{"deployment", "deploy DEPLOYMENT-ID", "workspace", "user", "organization"}, cmds[cmdIdx].Use) } diff --git a/cmd/cloud/workspace.go b/cmd/cloud/workspace.go index b52f14263..25ff9aaa8 100644 --- a/cmd/cloud/workspace.go +++ b/cmd/cloud/workspace.go @@ -589,7 +589,7 @@ func updateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro } cmd.SilenceUsage = true - return workspace.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, workspaceID, out, astroCoreClient) + return workspace.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, workspaceID, out, astroCoreClient, astroCoreIamClient) } func rotateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -599,7 +599,7 @@ func rotateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro tokenID = strings.ToLower(args[0]) } cmd.SilenceUsage = true - return workspace.RotateToken(tokenID, name, workspaceID, cleanTokenOutput, forceRotate, out, astroCoreClient) + return workspace.RotateToken(tokenID, name, workspaceID, cleanTokenOutput, forceRotate, out, astroCoreClient, astroCoreIamClient) } func deleteWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -610,7 +610,7 @@ func deleteWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro } cmd.SilenceUsage = true - return workspace.DeleteToken(tokenID, name, workspaceID, forceDelete, out, astroCoreClient) + return workspace.DeleteToken(tokenID, name, workspaceID, forceDelete, out, astroCoreClient, astroCoreIamClient) } func addOrgTokenToWorkspace(cmd *cobra.Command, args []string, out io.Writer) error { @@ -629,7 +629,7 @@ func addOrgTokenToWorkspace(cmd *cobra.Command, args []string, out io.Writer) er } } cmd.SilenceUsage = true - return organization.AddOrgTokenToWorkspace(orgTokenID, orgTokenName, tokenRole, workspaceID, out, astroCoreClient) + return organization.AddOrgTokenToWorkspace(orgTokenID, orgTokenName, tokenRole, workspaceID, out, astroCoreClient, astroCoreIamClient) } func coalesceWorkspace() (string, error) { diff --git a/cmd/root.go b/cmd/root.go index 41165f306..783a85b57 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -12,6 +12,7 @@ import ( airflowclient "github.com/astronomer/astro-cli/airflow-client" astrocore "github.com/astronomer/astro-cli/astro-client-core" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" astroplatformcore "github.com/astronomer/astro-cli/astro-client-platform-core" cloudCmd "github.com/astronomer/astro-cli/cmd/cloud" softwareCmd "github.com/astronomer/astro-cli/cmd/software" @@ -46,6 +47,7 @@ func NewRootCmd() *cobra.Command { airflowClient := airflowclient.NewAirflowClient(httputil.NewHTTPClient()) astroCoreClient := astrocore.NewCoreClient(httputil.NewHTTPClient()) + astroCoreIamClient := astroiamcore.NewIamCoreClient(httputil.NewHTTPClient()) platformCoreClient := astroplatformcore.NewPlatformCoreClient(httputil.NewHTTPClient()) ctx := cloudPlatform @@ -113,7 +115,7 @@ Welcome to the Astro CLI, the modern command line interface for data orchestrati if context.IsCloudContext() { // Include all the commands to be exposed for cloud users rootCmd.AddCommand( - cloudCmd.AddCmds(platformCoreClient, astroCoreClient, airflowClient, os.Stdout)..., + cloudCmd.AddCmds(platformCoreClient, astroCoreClient, airflowClient, astroCoreIamClient, os.Stdout)..., ) } else { // Include all the commands to be exposed for software users rootCmd.AddCommand( From b89a1989708878447253609af1692c2badc635da Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Fri, 5 Apr 2024 11:37:09 -0400 Subject: [PATCH 05/26] add list org and workspace tokens in deployment cmds --- astro-client-core/api.gen.go | 1684 ++++++++++++++++++++++---- cloud/deployment/deployment_token.go | 42 +- cloud/workspace/workspace_token.go | 24 +- cmd/cloud/deployment.go | 54 +- 4 files changed, 1539 insertions(+), 265 deletions(-) diff --git a/astro-client-core/api.gen.go b/astro-client-core/api.gen.go index d6e4a8853..9c4f04b9f 100644 --- a/astro-client-core/api.gen.go +++ b/astro-client-core/api.gen.go @@ -228,14 +228,15 @@ const ( const ( DefaultRoleScopeTypeDEPLOYMENT DefaultRoleScopeType = "DEPLOYMENT" DefaultRoleScopeTypeORGANIZATION DefaultRoleScopeType = "ORGANIZATION" + DefaultRoleScopeTypeSYSTEM DefaultRoleScopeType = "SYSTEM" DefaultRoleScopeTypeWORKSPACE DefaultRoleScopeType = "WORKSPACE" ) // Defines values for DeployStatus. const ( - DEPLOYED DeployStatus = "DEPLOYED" - FAILED DeployStatus = "FAILED" - INITIALIZED DeployStatus = "INITIALIZED" + DeployStatusDEPLOYED DeployStatus = "DEPLOYED" + DeployStatusFAILED DeployStatus = "FAILED" + DeployStatusINITIALIZED DeployStatus = "INITIALIZED" ) // Defines values for DeployType. @@ -249,6 +250,14 @@ const ( DeployGitProviderGITHUB DeployGitProvider = "GITHUB" ) +// Defines values for DeployStepStatus. +const ( + DeployStepStatusCOMPLETED DeployStepStatus = "COMPLETED" + DeployStepStatusFAILED DeployStepStatus = "FAILED" + DeployStepStatusPENDING DeployStepStatus = "PENDING" + DeployStepStatusRUNNING DeployStepStatus = "RUNNING" +) + // Defines values for DeploymentClusterCloudProvider. const ( DeploymentClusterCloudProviderAWS DeploymentClusterCloudProvider = "AWS" @@ -291,6 +300,14 @@ const ( WAKE DeploymentHibernationStatusNextEventType = "WAKE" ) +// Defines values for DeploymentIncidentSeverity. +const ( + Critical DeploymentIncidentSeverity = "critical" + Info DeploymentIncidentSeverity = "info" + Operations DeploymentIncidentSeverity = "operations" + Warning DeploymentIncidentSeverity = "warning" +) + // Defines values for DeploymentLogEntrySource. const ( DeploymentLogEntrySourceScheduler DeploymentLogEntrySource = "scheduler" @@ -420,6 +437,7 @@ const ( const ( RoleTemplateScopeTypeDEPLOYMENT RoleTemplateScopeType = "DEPLOYMENT" RoleTemplateScopeTypeORGANIZATION RoleTemplateScopeType = "ORGANIZATION" + RoleTemplateScopeTypeSYSTEM RoleTemplateScopeType = "SYSTEM" RoleTemplateScopeTypeWORKSPACE RoleTemplateScopeType = "WORKSPACE" ) @@ -737,6 +755,13 @@ const ( ListDeploymentsParamsSortsWorkspaceIdDesc ListDeploymentsParamsSorts = "workspaceId:desc" ) +// Defines values for ListDeploymentApiTokensParamsTokenTypes. +const ( + ListDeploymentApiTokensParamsTokenTypesDEPLOYMENT ListDeploymentApiTokensParamsTokenTypes = "DEPLOYMENT" + ListDeploymentApiTokensParamsTokenTypesORGANIZATION ListDeploymentApiTokensParamsTokenTypes = "ORGANIZATION" + ListDeploymentApiTokensParamsTokenTypesWORKSPACE ListDeploymentApiTokensParamsTokenTypes = "WORKSPACE" +) + // Defines values for ListDeploymentApiTokensParamsSorts. const ( ListDeploymentApiTokensParamsSortsCreatedAtAsc ListDeploymentApiTokensParamsSorts = "createdAt:asc" @@ -759,6 +784,22 @@ const ( ListDeploymentApiTokensParamsSortsUpdatedByIdDesc ListDeploymentApiTokensParamsSorts = "updatedById:desc" ) +// Defines values for ListDeployStepsParamsSorts. +const ( + ListDeployStepsParamsSortsCreatedAtAsc ListDeployStepsParamsSorts = "createdAt:asc" + ListDeployStepsParamsSortsCreatedAtDesc ListDeployStepsParamsSorts = "createdAt:desc" + ListDeployStepsParamsSortsEndedAtAsc ListDeployStepsParamsSorts = "endedAt:asc" + ListDeployStepsParamsSortsEndedAtDesc ListDeployStepsParamsSorts = "endedAt:desc" + ListDeployStepsParamsSortsStartedAtAsc ListDeployStepsParamsSorts = "startedAt:asc" + ListDeployStepsParamsSortsStartedAtDesc ListDeployStepsParamsSorts = "startedAt:desc" + ListDeployStepsParamsSortsStatusAsc ListDeployStepsParamsSorts = "status:asc" + ListDeployStepsParamsSortsStatusDesc ListDeployStepsParamsSorts = "status:desc" + ListDeployStepsParamsSortsTypeAsc ListDeployStepsParamsSorts = "type:asc" + ListDeployStepsParamsSortsTypeDesc ListDeployStepsParamsSorts = "type:desc" + ListDeployStepsParamsSortsUpdatedAtAsc ListDeployStepsParamsSorts = "updatedAt:asc" + ListDeployStepsParamsSortsUpdatedAtDesc ListDeployStepsParamsSorts = "updatedAt:desc" +) + // Defines values for GetDeploymentLogsParamsSources. const ( GetDeploymentLogsParamsSourcesScheduler GetDeploymentLogsParamsSources = "scheduler" @@ -824,9 +865,9 @@ const ( // Defines values for ListRolesParamsScopeTypes. const ( - DEPLOYMENT ListRolesParamsScopeTypes = "DEPLOYMENT" - ORGANIZATION ListRolesParamsScopeTypes = "ORGANIZATION" - WORKSPACE ListRolesParamsScopeTypes = "WORKSPACE" + ListRolesParamsScopeTypesDEPLOYMENT ListRolesParamsScopeTypes = "DEPLOYMENT" + ListRolesParamsScopeTypesORGANIZATION ListRolesParamsScopeTypes = "ORGANIZATION" + ListRolesParamsScopeTypesWORKSPACE ListRolesParamsScopeTypes = "WORKSPACE" ) // Defines values for ListRolesParamsSorts. @@ -910,6 +951,12 @@ const ( ListWorkspacesParamsSortsUpdatedAtDesc ListWorkspacesParamsSorts = "updatedAt:desc" ) +// Defines values for ListWorkspaceApiTokensParamsTokenTypes. +const ( + ORGANIZATION ListWorkspaceApiTokensParamsTokenTypes = "ORGANIZATION" + WORKSPACE ListWorkspaceApiTokensParamsTokenTypes = "WORKSPACE" +) + // Defines values for ListWorkspaceApiTokensParamsSorts. const ( ListWorkspaceApiTokensParamsSortsCreatedAtAsc ListWorkspaceApiTokensParamsSorts = "createdAt:asc" @@ -948,18 +995,18 @@ const ( // Defines values for ListWorkspaceUsersParamsSorts. const ( - CreatedAtAsc ListWorkspaceUsersParamsSorts = "createdAt:asc" - CreatedAtDesc ListWorkspaceUsersParamsSorts = "createdAt:desc" - FullNameAsc ListWorkspaceUsersParamsSorts = "fullName:asc" - FullNameDesc ListWorkspaceUsersParamsSorts = "fullName:desc" - StatusAsc ListWorkspaceUsersParamsSorts = "status:asc" - StatusDesc ListWorkspaceUsersParamsSorts = "status:desc" - UpdatedAtAsc ListWorkspaceUsersParamsSorts = "updatedAt:asc" - UpdatedAtDesc ListWorkspaceUsersParamsSorts = "updatedAt:desc" - UsernameAsc ListWorkspaceUsersParamsSorts = "username:asc" - UsernameDesc ListWorkspaceUsersParamsSorts = "username:desc" - WorkspaceRoleAsc ListWorkspaceUsersParamsSorts = "workspaceRole:asc" - WorkspaceRoleDesc ListWorkspaceUsersParamsSorts = "workspaceRole:desc" + ListWorkspaceUsersParamsSortsCreatedAtAsc ListWorkspaceUsersParamsSorts = "createdAt:asc" + ListWorkspaceUsersParamsSortsCreatedAtDesc ListWorkspaceUsersParamsSorts = "createdAt:desc" + ListWorkspaceUsersParamsSortsFullNameAsc ListWorkspaceUsersParamsSorts = "fullName:asc" + ListWorkspaceUsersParamsSortsFullNameDesc ListWorkspaceUsersParamsSorts = "fullName:desc" + ListWorkspaceUsersParamsSortsStatusAsc ListWorkspaceUsersParamsSorts = "status:asc" + ListWorkspaceUsersParamsSortsStatusDesc ListWorkspaceUsersParamsSorts = "status:desc" + ListWorkspaceUsersParamsSortsUpdatedAtAsc ListWorkspaceUsersParamsSorts = "updatedAt:asc" + ListWorkspaceUsersParamsSortsUpdatedAtDesc ListWorkspaceUsersParamsSorts = "updatedAt:desc" + ListWorkspaceUsersParamsSortsUsernameAsc ListWorkspaceUsersParamsSorts = "username:asc" + ListWorkspaceUsersParamsSortsUsernameDesc ListWorkspaceUsersParamsSorts = "username:desc" + ListWorkspaceUsersParamsSortsWorkspaceRoleAsc ListWorkspaceUsersParamsSorts = "workspaceRole:asc" + ListWorkspaceUsersParamsSortsWorkspaceRoleDesc ListWorkspaceUsersParamsSorts = "workspaceRole:desc" ) // Defines values for ListSelfUserRepositoriesParamsGitProvider. @@ -972,6 +1019,16 @@ const ( GetSelfUserRepositoryBranchParamsGitProviderGITHUB GetSelfUserRepositoryBranchParamsGitProvider = "GITHUB" ) +// Defines values for GetSelfUserGitAppAuthorizationParamsGitProvider. +const ( + GetSelfUserGitAppAuthorizationParamsGitProviderGITHUB GetSelfUserGitAppAuthorizationParamsGitProvider = "GITHUB" +) + +// Defines values for GetSelfUserGitAppInstallationParamsGitProvider. +const ( + GetSelfUserGitAppInstallationParamsGitProviderGITHUB GetSelfUserGitAppInstallationParamsGitProvider = "GITHUB" +) + // AddTeamMembersRequest defines model for AddTeamMembersRequest. type AddTeamMembersRequest struct { MemberIds []string `json:"memberIds"` @@ -1041,12 +1098,15 @@ type BasicSubjectProfileSubjectType string // Cluster defines model for Cluster. type Cluster struct { + AppliedHarmonyVersion *string `json:"appliedHarmonyVersion,omitempty"` AppliedTemplateVersion string `json:"appliedTemplateVersion"` CloudProvider ClusterCloudProvider `json:"cloudProvider"` Cohort *string `json:"cohort,omitempty"` CreatedAt time.Time `json:"createdAt"` DbInstanceType string `json:"dbInstanceType"` + DbInstanceVersion string `json:"dbInstanceVersion"` DeletedAt *string `json:"deletedAt,omitempty"` + HarmonyVersion *string `json:"harmonyVersion,omitempty"` Id string `json:"id"` IsCordoned *bool `json:"isCordoned,omitempty"` IsDryRun bool `json:"isDryRun"` @@ -1084,13 +1144,16 @@ type ClusterType string // ClusterDetailed defines model for ClusterDetailed. type ClusterDetailed struct { + AppliedHarmonyVersion *string `json:"appliedHarmonyVersion,omitempty"` AppliedTemplateVersion string `json:"appliedTemplateVersion"` CloudProvider ClusterDetailedCloudProvider `json:"cloudProvider"` Cohort *string `json:"cohort,omitempty"` CreatedAt time.Time `json:"createdAt"` CreatedBy BasicSubjectProfile `json:"createdBy"` DbInstanceType string `json:"dbInstanceType"` + DbInstanceVersion string `json:"dbInstanceVersion"` DeletedAt *string `json:"deletedAt,omitempty"` + HarmonyVersion *string `json:"harmonyVersion,omitempty"` Id string `json:"id"` IsCordoned *bool `json:"isCordoned,omitempty"` IsDryRun bool `json:"isDryRun"` @@ -1280,10 +1343,11 @@ type CreateClusterRouteRequestTargetType string // CreateCustomRoleRequest defines model for CreateCustomRoleRequest. type CreateCustomRoleRequest struct { - Description *string `json:"description,omitempty"` - Name string `json:"name"` - Permissions []string `json:"permissions"` - ScopeType CreateCustomRoleRequestScopeType `json:"scopeType"` + Description *string `json:"description,omitempty"` + Name string `json:"name"` + Permissions []string `json:"permissions"` + RestrictedWorkspaceIds *[]string `json:"restrictedWorkspaceIds,omitempty"` + ScopeType CreateCustomRoleRequestScopeType `json:"scopeType"` } // CreateCustomRoleRequestScopeType defines model for CreateCustomRoleRequest.ScopeType. @@ -1301,6 +1365,9 @@ type CreateDedicatedDeploymentRequest struct { // DefaultTaskPodCpu Must be valid kubernetes cpu resource string, at least 0.25 in terms of cpu cores DefaultTaskPodCpu string `json:"defaultTaskPodCpu"` + // DefaultTaskPodEphemeralStorage Must be valid kubernetes ephemeral storage resource string, in terms of Gibibytes (GiB) + DefaultTaskPodEphemeralStorage *string `json:"defaultTaskPodEphemeralStorage,omitempty"` + // DefaultTaskPodMemory Must be valid kubernetes memory resource string, at least 0.5Gi in terms of Gibibytes (GiB) DefaultTaskPodMemory string `json:"defaultTaskPodMemory"` @@ -1561,6 +1628,9 @@ type CreateStandardDeploymentRequest struct { // DefaultTaskPodCpu Must be valid kubernetes cpu resource string, at least 0.25 in terms of cpu cores DefaultTaskPodCpu string `json:"defaultTaskPodCpu"` + // DefaultTaskPodEphemeralStorage Must be valid kubernetes ephemeral storage resource string, in terms of Gibibytes (GiB) + DefaultTaskPodEphemeralStorage *string `json:"defaultTaskPodEphemeralStorage,omitempty"` + // DefaultTaskPodMemory Must be valid kubernetes memory resource string, at least 0.5Gi in terms of Gibibytes (GiB) DefaultTaskPodMemory string `json:"defaultTaskPodMemory"` @@ -1719,6 +1789,7 @@ type Deploy struct { RollbackFromId *string `json:"rollbackFromId,omitempty"` RuntimeVersion *string `json:"runtimeVersion,omitempty"` Status DeployStatus `json:"status"` + Steps *[]DeployStep `json:"steps,omitempty"` Type DeployType `json:"type"` UpdatedAt *time.Time `json:"updatedAt,omitempty"` UpdatedBySubject *BasicSubjectProfile `json:"updatedBySubject,omitempty"` @@ -1739,7 +1810,7 @@ type DeployGit struct { Branch string `json:"branch"` CommitSha string `json:"commitSha"` CommitUrl string `json:"commitUrl"` - Path string `json:"path"` + Path *string `json:"path,omitempty"` Provider DeployGitProvider `json:"provider"` Repo string `json:"repo"` } @@ -1753,64 +1824,103 @@ type DeployRollbackRequest struct { Description *string `json:"description,omitempty"` } +// DeployStep defines model for DeployStep. +type DeployStep struct { + CreatedAt time.Time `json:"createdAt"` + EmitsLogs *bool `json:"emitsLogs,omitempty"` + EndedAt *string `json:"endedAt,omitempty"` + Id string `json:"id"` + Label *string `json:"label,omitempty"` + StartedAt *string `json:"startedAt,omitempty"` + Status DeployStepStatus `json:"status"` + UpdatedAt time.Time `json:"updatedAt"` +} + +// DeployStepStatus defines model for DeployStep.Status. +type DeployStepStatus string + +// DeployStepLogEntry defines model for DeployStepLogEntry. +type DeployStepLogEntry struct { + Message string `json:"message"` + Timestamp time.Time `json:"timestamp"` +} + +// DeployStepLogsPaginated defines model for DeployStepLogsPaginated. +type DeployStepLogsPaginated struct { + Entries []DeployStepLogEntry `json:"entries"` + Limit int `json:"limit"` + Offset int `json:"offset"` + SearchId string `json:"searchId"` + TotalCount int `json:"totalCount"` +} + +// DeployStepsPaginated defines model for DeployStepsPaginated. +type DeployStepsPaginated struct { + DeploySteps []DeployStep `json:"deploySteps"` + Limit int `json:"limit"` + Offset int `json:"offset"` + TotalCount int `json:"totalCount"` +} + // Deployment defines model for Deployment. type Deployment struct { - AirflowVersion string `json:"airflowVersion"` - ClusterCloudProvider *DeploymentClusterCloudProvider `json:"clusterCloudProvider,omitempty"` - ClusterId string `json:"clusterId"` - ClusterName *string `json:"clusterName,omitempty"` - ClusterRegion *string `json:"clusterRegion,omitempty"` - ContactEmails []string `json:"contactEmails"` - CreatedAt time.Time `json:"createdAt"` - CreatedBy *BasicSubjectProfile `json:"createdBy,omitempty"` - CurrentDagTarballVersion *string `json:"currentDagTarballVersion,omitempty"` - CurrentEnvironmentSignatures *EnvironmentSignatures `json:"currentEnvironmentSignatures,omitempty"` - CurrentImageVersion *string `json:"currentImageVersion,omitempty"` - DefaultTaskPodCpu *string `json:"defaultTaskPodCpu,omitempty"` - DefaultTaskPodMemory *string `json:"defaultTaskPodMemory,omitempty"` - DeletedAt *time.Time `json:"deletedAt,omitempty"` - DeployId string `json:"deployId"` - Description *string `json:"description,omitempty"` - DesiredDagTarballVersion *string `json:"desiredDagTarballVersion,omitempty"` - DesiredEnvironmentSignatures *EnvironmentSignatures `json:"desiredEnvironmentSignatures,omitempty"` - DesiredImageVersion *string `json:"desiredImageVersion,omitempty"` - EnvironmentVariables *[]DeploymentEnvironmentVariable `json:"environmentVariables,omitempty"` - Executor *DeploymentExecutor `json:"executor,omitempty"` - ExternalIPs *[]string `json:"externalIPs,omitempty"` - Id string `json:"id"` - ImageId string `json:"imageId"` - ImageRepository string `json:"imageRepository"` - ImageTag string `json:"imageTag"` - IsCicdEnforced bool `json:"isCicdEnforced"` - IsDagDeployEnabled bool `json:"isDagDeployEnabled"` - IsDevelopmentOnly bool `json:"isDevelopmentOnly"` - IsHighAvailability *bool `json:"isHighAvailability,omitempty"` - LaminarHealthStatus *LaminarHealthStatus `json:"laminarHealthStatus,omitempty"` - Name string `json:"name"` - OidcIssuerUrl *string `json:"oidcIssuerUrl,omitempty"` - OrganizationId string `json:"organizationId"` - OrganizationName string `json:"organizationName"` - OrganizationShortName string `json:"organizationShortName"` - ReleaseName string `json:"releaseName"` - RepositoryBranch *string `json:"repositoryBranch,omitempty"` - RepositoryPathDetails *DeploymentRepositoryPath `json:"repositoryPathDetails,omitempty"` - RepositoryPathId *string `json:"repositoryPathId,omitempty"` - ResourceQuotaCpu *string `json:"resourceQuotaCpu,omitempty"` - ResourceQuotaMemory *string `json:"resourceQuotaMemory,omitempty"` - RuntimeVersion string `json:"runtimeVersion"` - ScalingSpec *DeploymentScalingSpec `json:"scalingSpec,omitempty"` - ScalingStatus *DeploymentScalingStatus `json:"scalingStatus,omitempty"` - SchedulerAu *int `json:"schedulerAu,omitempty"` - SchedulerCpu string `json:"schedulerCpu"` - SchedulerMemory string `json:"schedulerMemory"` - SchedulerReplicas int `json:"schedulerReplicas"` - SchedulerSize *DeploymentSchedulerSize `json:"schedulerSize,omitempty"` - Status DeploymentStatus `json:"status"` - StatusReason *string `json:"statusReason,omitempty"` - TaskPodNodePoolId *string `json:"taskPodNodePoolId,omitempty"` - Type *DeploymentType `json:"type,omitempty"` - UpdatedAt time.Time `json:"updatedAt"` - UpdatedBy *BasicSubjectProfile `json:"updatedBy,omitempty"` + AirflowVersion string `json:"airflowVersion"` + ClusterCloudProvider *DeploymentClusterCloudProvider `json:"clusterCloudProvider,omitempty"` + ClusterId string `json:"clusterId"` + ClusterName *string `json:"clusterName,omitempty"` + ClusterRegion *string `json:"clusterRegion,omitempty"` + ContactEmails []string `json:"contactEmails"` + CreatedAt time.Time `json:"createdAt"` + CreatedBy *BasicSubjectProfile `json:"createdBy,omitempty"` + CurrentDagTarballVersion *string `json:"currentDagTarballVersion,omitempty"` + CurrentEnvironmentSignatures *EnvironmentSignatures `json:"currentEnvironmentSignatures,omitempty"` + CurrentImageVersion *string `json:"currentImageVersion,omitempty"` + DefaultTaskPodCpu *string `json:"defaultTaskPodCpu,omitempty"` + DefaultTaskPodEphemeralStorage *string `json:"defaultTaskPodEphemeralStorage,omitempty"` + DefaultTaskPodMemory *string `json:"defaultTaskPodMemory,omitempty"` + DeletedAt *time.Time `json:"deletedAt,omitempty"` + DeployId string `json:"deployId"` + DeploymentHealthStatus *DeploymentHealthStatus `json:"deploymentHealthStatus,omitempty"` + Description *string `json:"description,omitempty"` + DesiredDagTarballVersion *string `json:"desiredDagTarballVersion,omitempty"` + DesiredEnvironmentSignatures *EnvironmentSignatures `json:"desiredEnvironmentSignatures,omitempty"` + DesiredImageVersion *string `json:"desiredImageVersion,omitempty"` + EnvironmentVariables *[]DeploymentEnvironmentVariable `json:"environmentVariables,omitempty"` + Executor *DeploymentExecutor `json:"executor,omitempty"` + ExternalIPs *[]string `json:"externalIPs,omitempty"` + Id string `json:"id"` + ImageId string `json:"imageId"` + ImageRepository string `json:"imageRepository"` + ImageTag string `json:"imageTag"` + IsCicdEnforced bool `json:"isCicdEnforced"` + IsDagDeployEnabled bool `json:"isDagDeployEnabled"` + IsDevelopmentOnly bool `json:"isDevelopmentOnly"` + IsHighAvailability *bool `json:"isHighAvailability,omitempty"` + Name string `json:"name"` + OidcIssuerUrl *string `json:"oidcIssuerUrl,omitempty"` + OrganizationId string `json:"organizationId"` + OrganizationName string `json:"organizationName"` + OrganizationShortName string `json:"organizationShortName"` + ReleaseName string `json:"releaseName"` + RepositoryBranch *string `json:"repositoryBranch,omitempty"` + RepositoryPathDetails *DeploymentRepositoryPath `json:"repositoryPathDetails,omitempty"` + RepositoryPathId *string `json:"repositoryPathId,omitempty"` + ResourceQuotaCpu *string `json:"resourceQuotaCpu,omitempty"` + ResourceQuotaMemory *string `json:"resourceQuotaMemory,omitempty"` + RuntimeVersion string `json:"runtimeVersion"` + ScalingSpec *DeploymentScalingSpec `json:"scalingSpec,omitempty"` + ScalingStatus *DeploymentScalingStatus `json:"scalingStatus,omitempty"` + SchedulerAu *int `json:"schedulerAu,omitempty"` + SchedulerCpu string `json:"schedulerCpu"` + SchedulerMemory string `json:"schedulerMemory"` + SchedulerReplicas int `json:"schedulerReplicas"` + SchedulerSize *DeploymentSchedulerSize `json:"schedulerSize,omitempty"` + Status DeploymentStatus `json:"status"` + StatusReason *string `json:"statusReason,omitempty"` + TaskPodNodePoolId *string `json:"taskPodNodePoolId,omitempty"` + Type *DeploymentType `json:"type,omitempty"` + UpdatedAt time.Time `json:"updatedAt"` + UpdatedBy *BasicSubjectProfile `json:"updatedBy,omitempty"` // WebServerAirflowApiUrl The Deployment's webserver's base url to directly access the Airflow api. WebServerAirflowApiUrl string `json:"webServerAirflowApiUrl"` @@ -1855,6 +1965,13 @@ type DeploymentEnvironmentVariableRequest struct { Value *string `json:"value,omitempty"` } +// DeploymentHealthStatus defines model for DeploymentHealthStatus. +type DeploymentHealthStatus struct { + HibernationStatus *HibernationStatus `json:"hibernationStatus,omitempty"` + Incidents *[]DeploymentIncident `json:"incidents,omitempty"` + Info *DeploymentInfo `json:"info,omitempty"` +} + // DeploymentHibernationOverride defines model for DeploymentHibernationOverride. type DeploymentHibernationOverride struct { // Hibernate Whether to go into hibernation or not via the override rule @@ -1925,6 +2042,30 @@ type DeploymentHibernationStatus struct { // DeploymentHibernationStatusNextEventType Represents the type of the scheduled event for the deployment, one of HIBERNATE or WAKE type DeploymentHibernationStatusNextEventType string +// DeploymentIncident defines model for DeploymentIncident. +type DeploymentIncident struct { + CreatedAt time.Time `json:"createdAt"` + DeploymentId string `json:"deploymentId"` + Description string `json:"description"` + EnabledForOrg bool `json:"enabledForOrg"` + IncidentData *map[string]interface{} `json:"incidentData,omitempty"` + IncidentType string `json:"incidentType"` + ResolvedAt *time.Time `json:"resolvedAt,omitempty"` + Severity DeploymentIncidentSeverity `json:"severity"` + Subject string `json:"subject"` + UpdatedAt *time.Time `json:"updatedAt,omitempty"` + WorkspaceId *string `json:"workspaceId,omitempty"` +} + +// DeploymentIncidentSeverity defines model for DeploymentIncident.Severity. +type DeploymentIncidentSeverity string + +// DeploymentInfo defines model for DeploymentInfo. +type DeploymentInfo struct { + AirflowStatus *map[string]interface{} `json:"airflowStatus,omitempty"` + Scaling *map[string]interface{} `json:"scaling,omitempty"` +} + // DeploymentInstanceSpecRequest defines model for DeploymentInstanceSpecRequest. type DeploymentInstanceSpecRequest struct { Au int `json:"au"` @@ -1967,7 +2108,7 @@ type DeploymentOptions struct { // DeploymentRepositoryPath defines model for DeploymentRepositoryPath. type DeploymentRepositoryPath struct { GitAccount string `json:"gitAccount"` - GitPath string `json:"gitPath"` + GitPath *string `json:"gitPath,omitempty"` GitProvider DeploymentRepositoryPathGitProvider `json:"gitProvider"` GitRepository string `json:"gitRepository"` } @@ -2113,6 +2254,16 @@ type FeatureFlag struct { // GenericJSON defines model for GenericJSON. type GenericJSON map[string]interface{} +// GitApplicationAuthorization defines model for GitApplicationAuthorization. +type GitApplicationAuthorization struct { + Url string `json:"url"` +} + +// GitApplicationInstallation defines model for GitApplicationInstallation. +type GitApplicationInstallation struct { + Url string `json:"url"` +} + // GitHubAccount defines model for GitHubAccount. type GitHubAccount struct { AccountName string `json:"accountName"` @@ -2135,6 +2286,14 @@ type GitRepository struct { UserIsAdmin bool `json:"userIsAdmin"` } +// HibernationStatus defines model for HibernationStatus. +type HibernationStatus struct { + IsHibernating *bool `json:"isHibernating,omitempty"` + NextEventAt *time.Time `json:"nextEventAt,omitempty"` + NextEventType *string `json:"nextEventType,omitempty"` + Reason *string `json:"reason,omitempty"` +} + // Invite defines model for Invite. type Invite struct { ExpiresAt string `json:"expiresAt"` @@ -2155,13 +2314,6 @@ type Invite struct { UserId *string `json:"userId,omitempty"` } -// LaminarHealthStatus defines model for LaminarHealthStatus. -type LaminarHealthStatus struct { - Incidents *[]map[string]interface{} `json:"incidents,omitempty"` - Info *map[string]interface{} `json:"info,omitempty"` - Operations *map[string]interface{} `json:"operations,omitempty"` -} - // LegacyAstroOptions defines model for LegacyAstroOptions. type LegacyAstroOptions struct { AstroUnitCpuMilli float32 `json:"astroUnitCpuMilli"` @@ -2289,6 +2441,7 @@ type Organization struct { EnvironmentSecretsShowable bool `json:"environmentSecretsShowable"` Id string `json:"id"` IsAzureManaged *bool `json:"isAzureManaged,omitempty"` + IsEgressChargebackEnabled *bool `json:"isEgressChargebackEnabled,omitempty"` IsScimEnabled bool `json:"isScimEnabled"` ManagedDomains *[]ManagedDomain `json:"managedDomains,omitempty"` MetronomeId *string `json:"metronomeId,omitempty"` @@ -2401,14 +2554,15 @@ type ResourceRange struct { // Role defines model for Role. type Role struct { - CreatedAt string `json:"createdAt"` - CreatedBy BasicSubjectProfile `json:"createdBy"` - Description *string `json:"description,omitempty"` - Id string `json:"id"` - Name string `json:"name"` - ScopeType RoleScopeType `json:"scopeType"` - UpdatedAt string `json:"updatedAt"` - UpdatedBy BasicSubjectProfile `json:"updatedBy"` + CreatedAt string `json:"createdAt"` + CreatedBy BasicSubjectProfile `json:"createdBy"` + Description *string `json:"description,omitempty"` + Id string `json:"id"` + Name string `json:"name"` + RestrictedWorkspaceIds []string `json:"restrictedWorkspaceIds"` + ScopeType RoleScopeType `json:"scopeType"` + UpdatedAt string `json:"updatedAt"` + UpdatedBy BasicSubjectProfile `json:"updatedBy"` } // RoleScopeType defines model for Role.ScopeType. @@ -2456,15 +2610,16 @@ type RoleTemplateScopeType string // RoleWithPermission defines model for RoleWithPermission. type RoleWithPermission struct { - CreatedAt string `json:"createdAt"` - CreatedBy BasicSubjectProfile `json:"createdBy"` - Description *string `json:"description,omitempty"` - Id string `json:"id"` - Name string `json:"name"` - Permissions []string `json:"permissions"` - ScopeType RoleWithPermissionScopeType `json:"scopeType"` - UpdatedAt string `json:"updatedAt"` - UpdatedBy BasicSubjectProfile `json:"updatedBy"` + CreatedAt string `json:"createdAt"` + CreatedBy BasicSubjectProfile `json:"createdBy"` + Description *string `json:"description,omitempty"` + Id string `json:"id"` + Name string `json:"name"` + Permissions []string `json:"permissions"` + RestrictedWorkspaceIds []string `json:"restrictedWorkspaceIds"` + ScopeType RoleWithPermissionScopeType `json:"scopeType"` + UpdatedAt string `json:"updatedAt"` + UpdatedBy BasicSubjectProfile `json:"updatedBy"` } // RoleWithPermissionScopeType defines model for RoleWithPermission.ScopeType. @@ -2534,6 +2689,7 @@ type SharedCluster struct { Cohort *string `json:"cohort,omitempty"` CreatedAt time.Time `json:"createdAt"` DbInstanceType string `json:"dbInstanceType"` + DbInstanceVersion string `json:"dbInstanceVersion"` Id string `json:"id"` IsCordoned *bool `json:"isCordoned,omitempty"` IsDryRun bool `json:"isDryRun"` @@ -2637,29 +2793,32 @@ type TransferDeploymentRequest struct { // UpdateAwsClusterRequest defines model for UpdateAwsClusterRequest. type UpdateAwsClusterRequest struct { - DbInstanceType string `json:"dbInstanceType"` - K8sTags []ClusterTag `json:"k8sTags"` - Name string `json:"name"` - NodePools []UpdateNodePoolRequest `json:"nodePools"` - TemplateVersion string `json:"templateVersion"` - Workspaces *[]string `json:"workspaces,omitempty"` + DbInstanceType string `json:"dbInstanceType"` + DbInstanceVersion *string `json:"dbInstanceVersion,omitempty"` + K8sTags []ClusterTag `json:"k8sTags"` + Name string `json:"name"` + NodePools []UpdateNodePoolRequest `json:"nodePools"` + TemplateVersion string `json:"templateVersion"` + Workspaces *[]string `json:"workspaces,omitempty"` } // UpdateAzureClusterRequest defines model for UpdateAzureClusterRequest. type UpdateAzureClusterRequest struct { - DbInstanceType string `json:"dbInstanceType"` - K8sTags []ClusterTag `json:"k8sTags"` - Name string `json:"name"` - NodePools []UpdateNodePoolRequest `json:"nodePools"` - TemplateVersion string `json:"templateVersion"` - Workspaces *[]string `json:"workspaces,omitempty"` + DbInstanceType string `json:"dbInstanceType"` + DbInstanceVersion *string `json:"dbInstanceVersion,omitempty"` + K8sTags []ClusterTag `json:"k8sTags"` + Name string `json:"name"` + NodePools []UpdateNodePoolRequest `json:"nodePools"` + TemplateVersion string `json:"templateVersion"` + Workspaces *[]string `json:"workspaces,omitempty"` } // UpdateCustomRoleRequest defines model for UpdateCustomRoleRequest. type UpdateCustomRoleRequest struct { - Description *string `json:"description,omitempty"` - Name string `json:"name"` - Permissions []string `json:"permissions"` + Description *string `json:"description,omitempty"` + Name string `json:"name"` + Permissions []string `json:"permissions"` + RestrictedWorkspaceIds *[]string `json:"restrictedWorkspaceIds,omitempty"` } // UpdateDeployRequest defines model for UpdateDeployRequest. @@ -2749,12 +2908,13 @@ type UpdateEnvironmentObjectRequestScope string // UpdateGcpClusterRequest defines model for UpdateGcpClusterRequest. type UpdateGcpClusterRequest struct { - DbInstanceType string `json:"dbInstanceType"` - K8sTags []ClusterTag `json:"k8sTags"` - Name string `json:"name"` - NodePools []UpdateNodePoolRequest `json:"nodePools"` - TemplateVersion string `json:"templateVersion"` - Workspaces *[]string `json:"workspaces,omitempty"` + DbInstanceType string `json:"dbInstanceType"` + DbInstanceVersion *string `json:"dbInstanceVersion,omitempty"` + K8sTags []ClusterTag `json:"k8sTags"` + Name string `json:"name"` + NodePools []UpdateNodePoolRequest `json:"nodePools"` + TemplateVersion string `json:"templateVersion"` + Workspaces *[]string `json:"workspaces,omitempty"` } // UpdateHostedDeploymentRequest defines model for UpdateHostedDeploymentRequest. @@ -2764,6 +2924,9 @@ type UpdateHostedDeploymentRequest struct { // DefaultTaskPodCpu Must be valid kubernetes cpu resource string, at least 0.25 in terms of cpu cores DefaultTaskPodCpu string `json:"defaultTaskPodCpu"` + // DefaultTaskPodEphemeralStorage Must be valid kubernetes ephemeral storage resource string, in terms of Gibibytes (GiB) + DefaultTaskPodEphemeralStorage *string `json:"defaultTaskPodEphemeralStorage,omitempty"` + // DefaultTaskPodMemory Must be valid kubernetes memory resource string, at least 0.5Gi in terms of Gibibytes (GiB) DefaultTaskPodMemory string `json:"defaultTaskPodMemory"` Description *string `json:"description,omitempty"` @@ -3256,6 +3419,9 @@ type ListDeploymentsParams struct { // WorkspaceIds IDs that define the workspaces where deployments belong to WorkspaceIds *[]string `form:"workspaceIds,omitempty" json:"workspaceIds,omitempty"` + // Names deployment names to filter on + Names *[]string `form:"names,omitempty" json:"names,omitempty"` + // Offset offset for pagination Offset *int `form:"offset,omitempty" json:"offset,omitempty"` @@ -3271,6 +3437,9 @@ type ListDeploymentsParamsSorts string // ListDeploymentApiTokensParams defines parameters for ListDeploymentApiTokens. type ListDeploymentApiTokensParams struct { + // TokenTypes filters result set to the passed in token types + TokenTypes *[]ListDeploymentApiTokensParamsTokenTypes `form:"tokenTypes,omitempty" json:"tokenTypes,omitempty"` + // Offset Offset for pagination Offset *int `form:"offset,omitempty" json:"offset,omitempty"` @@ -3281,6 +3450,9 @@ type ListDeploymentApiTokensParams struct { Sorts *[]ListDeploymentApiTokensParamsSorts `form:"sorts,omitempty" json:"sorts,omitempty"` } +// ListDeploymentApiTokensParamsTokenTypes defines parameters for ListDeploymentApiTokens. +type ListDeploymentApiTokensParamsTokenTypes string + // ListDeploymentApiTokensParamsSorts defines parameters for ListDeploymentApiTokens. type ListDeploymentApiTokensParamsSorts string @@ -3299,6 +3471,39 @@ type ListDeploysParams struct { SubjectId *string `form:"subjectId,omitempty" json:"subjectId,omitempty"` } +// GetDeployParams defines parameters for GetDeploy. +type GetDeployParams struct { + // IncludeSteps whether to include the deploy steps + IncludeSteps *bool `form:"includeSteps,omitempty" json:"includeSteps,omitempty"` +} + +// ListDeployStepsParams defines parameters for ListDeploySteps. +type ListDeployStepsParams struct { + // Offset offset for pagination + Offset *int `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit limit for pagination + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + + // Sorts sorting criteria, each criterion should conform to format 'fieldName:asc' or 'fieldName:desc' + Sorts *[]ListDeployStepsParamsSorts `form:"sorts,omitempty" json:"sorts,omitempty"` +} + +// ListDeployStepsParamsSorts defines parameters for ListDeploySteps. +type ListDeployStepsParamsSorts string + +// ListDeployStepLogsParams defines parameters for ListDeployStepLogs. +type ListDeployStepLogsParams struct { + // Limit limit of the count of the logs + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + + // Offset offset of the log entries + Offset *int `form:"offset,omitempty" json:"offset,omitempty"` + + // SearchId searchId to get logs from + SearchId *string `form:"searchId,omitempty" json:"searchId,omitempty"` +} + // GetDeploymentLogsParams defines parameters for GetDeploymentLogs. type GetDeploymentLogsParams struct { // Sources log sources to select logs from @@ -3520,6 +3725,9 @@ type ListWorkspacesParams struct { // WorkspaceIds list of workspace ids to get detail of WorkspaceIds *[]string `form:"workspaceIds,omitempty" json:"workspaceIds,omitempty"` + // Names names to filter on + Names *[]string `form:"names,omitempty" json:"names,omitempty"` + // Offset offset for pagination Offset *int `form:"offset,omitempty" json:"offset,omitempty"` @@ -3538,6 +3746,9 @@ type ListWorkspacesParamsSorts string // ListWorkspaceApiTokensParams defines parameters for ListWorkspaceApiTokens. type ListWorkspaceApiTokensParams struct { + // TokenTypes filters result set to the passed in token types + TokenTypes *[]ListWorkspaceApiTokensParamsTokenTypes `form:"tokenTypes,omitempty" json:"tokenTypes,omitempty"` + // Offset Offset for pagination Offset *int `form:"offset,omitempty" json:"offset,omitempty"` @@ -3548,6 +3759,9 @@ type ListWorkspaceApiTokensParams struct { Sorts *[]ListWorkspaceApiTokensParamsSorts `form:"sorts,omitempty" json:"sorts,omitempty"` } +// ListWorkspaceApiTokensParamsTokenTypes defines parameters for ListWorkspaceApiTokens. +type ListWorkspaceApiTokensParamsTokenTypes string + // ListWorkspaceApiTokensParamsSorts defines parameters for ListWorkspaceApiTokens. type ListWorkspaceApiTokensParamsSorts string @@ -3656,6 +3870,12 @@ type ListSelfUserRepositoriesParamsGitProvider string // GetSelfUserRepositoryBranchParamsGitProvider defines parameters for GetSelfUserRepositoryBranch. type GetSelfUserRepositoryBranchParamsGitProvider string +// GetSelfUserGitAppAuthorizationParamsGitProvider defines parameters for GetSelfUserGitAppAuthorization. +type GetSelfUserGitAppAuthorizationParamsGitProvider string + +// GetSelfUserGitAppInstallationParamsGitProvider defines parameters for GetSelfUserGitAppInstallation. +type GetSelfUserGitAppInstallationParamsGitProvider string + // CreateOrganizationJSONRequestBody defines body for CreateOrganization for application/json ContentType. type CreateOrganizationJSONRequestBody = CreateOrganizationRequest @@ -4212,11 +4432,20 @@ type ClientInterface interface { CreateDeploy(ctx context.Context, organizationId string, deploymentId string, body CreateDeployJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetDeploy request + GetDeploy(ctx context.Context, organizationId string, deploymentId string, deployId string, params *GetDeployParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // UpdateDeploy request with any body UpdateDeployWithBody(ctx context.Context, organizationId string, deploymentId string, deployId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) UpdateDeploy(ctx context.Context, organizationId string, deploymentId string, deployId string, body UpdateDeployJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListDeploySteps request + ListDeploySteps(ctx context.Context, organizationId string, deploymentId string, deployId string, params *ListDeployStepsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListDeployStepLogs request + ListDeployStepLogs(ctx context.Context, organizationId string, deploymentId string, deployId string, deployStepId string, params *ListDeployStepLogsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetDeploymentHealth request GetDeploymentHealth(ctx context.Context, organizationId string, deploymentId string, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -4426,6 +4655,12 @@ type ClientInterface interface { // GetSelfUserRepositoryBranch request GetSelfUserRepositoryBranch(ctx context.Context, gitProvider GetSelfUserRepositoryBranchParamsGitProvider, gitAccount string, gitRepository string, gitBranch string, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetSelfUserGitAppAuthorization request + GetSelfUserGitAppAuthorization(ctx context.Context, gitProvider GetSelfUserGitAppAuthorizationParamsGitProvider, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetSelfUserGitAppInstallation request + GetSelfUserGitAppInstallation(ctx context.Context, gitProvider GetSelfUserGitAppInstallationParamsGitProvider, reqEditors ...RequestEditorFn) (*http.Response, error) + // UpdateSelfUserInvite request with any body UpdateSelfUserInviteWithBody(ctx context.Context, inviteId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -5128,6 +5363,18 @@ func (c *Client) CreateDeploy(ctx context.Context, organizationId string, deploy return c.Client.Do(req) } +func (c *Client) GetDeploy(ctx context.Context, organizationId string, deploymentId string, deployId string, params *GetDeployParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetDeployRequest(c.Server, organizationId, deploymentId, deployId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) UpdateDeployWithBody(ctx context.Context, organizationId string, deploymentId string, deployId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewUpdateDeployRequestWithBody(c.Server, organizationId, deploymentId, deployId, contentType, body) if err != nil { @@ -5152,6 +5399,30 @@ func (c *Client) UpdateDeploy(ctx context.Context, organizationId string, deploy return c.Client.Do(req) } +func (c *Client) ListDeploySteps(ctx context.Context, organizationId string, deploymentId string, deployId string, params *ListDeployStepsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListDeployStepsRequest(c.Server, organizationId, deploymentId, deployId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListDeployStepLogs(ctx context.Context, organizationId string, deploymentId string, deployId string, deployStepId string, params *ListDeployStepLogsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListDeployStepLogsRequest(c.Server, organizationId, deploymentId, deployId, deployStepId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) GetDeploymentHealth(ctx context.Context, organizationId string, deploymentId string, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewGetDeploymentHealthRequest(c.Server, organizationId, deploymentId) if err != nil { @@ -6064,6 +6335,30 @@ func (c *Client) GetSelfUserRepositoryBranch(ctx context.Context, gitProvider Ge return c.Client.Do(req) } +func (c *Client) GetSelfUserGitAppAuthorization(ctx context.Context, gitProvider GetSelfUserGitAppAuthorizationParamsGitProvider, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetSelfUserGitAppAuthorizationRequest(c.Server, gitProvider) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetSelfUserGitAppInstallation(ctx context.Context, gitProvider GetSelfUserGitAppInstallationParamsGitProvider, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetSelfUserGitAppInstallationRequest(c.Server, gitProvider) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) UpdateSelfUserInviteWithBody(ctx context.Context, inviteId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewUpdateSelfUserInviteRequestWithBody(c.Server, inviteId, contentType, body) if err != nil { @@ -7744,6 +8039,22 @@ func NewListDeploymentsRequest(server string, organizationId string, params *Lis } + if params.Names != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "names", runtime.ParamLocationQuery, *params.Names); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + if params.Offset != nil { if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { @@ -8020,6 +8331,22 @@ func NewListDeploymentApiTokensRequest(server string, organizationId string, dep queryValues := queryURL.Query() + if params.TokenTypes != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "tokenTypes", runtime.ParamLocationQuery, *params.TokenTypes); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + if params.Offset != nil { if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { @@ -8554,19 +8881,8 @@ func NewCreateDeployRequestWithBody(server string, organizationId string, deploy return req, nil } -// NewUpdateDeployRequest calls the generic UpdateDeploy builder with application/json body -func NewUpdateDeployRequest(server string, organizationId string, deploymentId string, deployId string, body UpdateDeployJSONRequestBody) (*http.Request, error) { - var bodyReader io.Reader - buf, err := json.Marshal(body) - if err != nil { - return nil, err - } - bodyReader = bytes.NewReader(buf) - return NewUpdateDeployRequestWithBody(server, organizationId, deploymentId, deployId, "application/json", bodyReader) -} - -// NewUpdateDeployRequestWithBody generates requests for UpdateDeploy with any type of body -func NewUpdateDeployRequestWithBody(server string, organizationId string, deploymentId string, deployId string, contentType string, body io.Reader) (*http.Request, error) { +// NewGetDeployRequest generates requests for GetDeploy +func NewGetDeployRequest(server string, organizationId string, deploymentId string, deployId string, params *GetDeployParams) (*http.Request, error) { var err error var pathParam0 string @@ -8605,18 +8921,47 @@ func NewUpdateDeployRequestWithBody(server string, organizationId string, deploy return nil, err } - req, err := http.NewRequest("POST", queryURL.String(), body) + queryValues := queryURL.Query() + + if params.IncludeSteps != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "includeSteps", runtime.ParamLocationQuery, *params.IncludeSteps); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("GET", queryURL.String(), nil) if err != nil { return nil, err } - req.Header.Add("Content-Type", contentType) - return req, nil } -// NewGetDeploymentHealthRequest generates requests for GetDeploymentHealth -func NewGetDeploymentHealthRequest(server string, organizationId string, deploymentId string) (*http.Request, error) { +// NewUpdateDeployRequest calls the generic UpdateDeploy builder with application/json body +func NewUpdateDeployRequest(server string, organizationId string, deploymentId string, deployId string, body UpdateDeployJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateDeployRequestWithBody(server, organizationId, deploymentId, deployId, "application/json", bodyReader) +} + +// NewUpdateDeployRequestWithBody generates requests for UpdateDeploy with any type of body +func NewUpdateDeployRequestWithBody(server string, organizationId string, deploymentId string, deployId string, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -8633,12 +8978,19 @@ func NewGetDeploymentHealthRequest(server string, organizationId string, deploym return nil, err } + var pathParam2 string + + pathParam2, err = runtime.StyleParamWithLocation("simple", false, "deployId", runtime.ParamLocationPath, deployId) + if err != nil { + return nil, err + } + serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/organizations/%s/deployments/%s/health", pathParam0, pathParam1) + operationPath := fmt.Sprintf("/organizations/%s/deployments/%s/deploys/%s", pathParam0, pathParam1, pathParam2) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -8648,16 +9000,18 @@ func NewGetDeploymentHealthRequest(server string, organizationId string, deploym return nil, err } - req, err := http.NewRequest("GET", queryURL.String(), nil) + req, err := http.NewRequest("POST", queryURL.String(), body) if err != nil { return nil, err } + req.Header.Add("Content-Type", contentType) + return req, nil } -// NewGetDeploymentLogsRequest generates requests for GetDeploymentLogs -func NewGetDeploymentLogsRequest(server string, organizationId string, deploymentId string, params *GetDeploymentLogsParams) (*http.Request, error) { +// NewListDeployStepsRequest generates requests for ListDeploySteps +func NewListDeployStepsRequest(server string, organizationId string, deploymentId string, deployId string, params *ListDeployStepsParams) (*http.Request, error) { var err error var pathParam0 string @@ -8674,12 +9028,19 @@ func NewGetDeploymentLogsRequest(server string, organizationId string, deploymen return nil, err } + var pathParam2 string + + pathParam2, err = runtime.StyleParamWithLocation("simple", false, "deployId", runtime.ParamLocationPath, deployId) + if err != nil { + return nil, err + } + serverURL, err := url.Parse(server) if err != nil { return nil, err } - operationPath := fmt.Sprintf("/organizations/%s/deployments/%s/logs", pathParam0, pathParam1) + operationPath := fmt.Sprintf("/organizations/%s/deployments/%s/deploys/%s/steps", pathParam0, pathParam1, pathParam2) if operationPath[0] == '/' { operationPath = "." + operationPath } @@ -8691,21 +9052,9 @@ func NewGetDeploymentLogsRequest(server string, organizationId string, deploymen queryValues := queryURL.Query() - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "sources", runtime.ParamLocationQuery, params.Sources); err != nil { - return nil, err - } else if parsed, err := url.ParseQuery(queryFrag); err != nil { - return nil, err - } else { - for k, v := range parsed { - for _, v2 := range v { - queryValues.Add(k, v2) - } - } - } - - if params.Limit != nil { + if params.Offset != nil { - if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.Limit); err != nil { + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { return nil, err } else if parsed, err := url.ParseQuery(queryFrag); err != nil { return nil, err @@ -8719,7 +9068,260 @@ func NewGetDeploymentLogsRequest(server string, organizationId string, deploymen } - if params.Offset != nil { + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.Limit); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.Sorts != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "sorts", runtime.ParamLocationQuery, *params.Sorts); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListDeployStepLogsRequest generates requests for ListDeployStepLogs +func NewListDeployStepLogsRequest(server string, organizationId string, deploymentId string, deployId string, deployStepId string, params *ListDeployStepLogsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "deploymentId", runtime.ParamLocationPath, deploymentId) + if err != nil { + return nil, err + } + + var pathParam2 string + + pathParam2, err = runtime.StyleParamWithLocation("simple", false, "deployId", runtime.ParamLocationPath, deployId) + if err != nil { + return nil, err + } + + var pathParam3 string + + pathParam3, err = runtime.StyleParamWithLocation("simple", false, "deployStepId", runtime.ParamLocationPath, deployStepId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/organizations/%s/deployments/%s/deploys/%s/steps/%s/logs", pathParam0, pathParam1, pathParam2, pathParam3) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + queryValues := queryURL.Query() + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.Limit); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.SearchId != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "searchId", runtime.ParamLocationQuery, *params.SearchId); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetDeploymentHealthRequest generates requests for GetDeploymentHealth +func NewGetDeploymentHealthRequest(server string, organizationId string, deploymentId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "deploymentId", runtime.ParamLocationPath, deploymentId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/organizations/%s/deployments/%s/health", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetDeploymentLogsRequest generates requests for GetDeploymentLogs +func NewGetDeploymentLogsRequest(server string, organizationId string, deploymentId string, params *GetDeploymentLogsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "organizationId", runtime.ParamLocationPath, organizationId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "deploymentId", runtime.ParamLocationPath, deploymentId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/organizations/%s/deployments/%s/logs", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + queryValues := queryURL.Query() + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "sources", runtime.ParamLocationQuery, params.Sources); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "limit", runtime.ParamLocationQuery, *params.Limit); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + if params.Offset != nil { if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { return nil, err @@ -11029,6 +11631,22 @@ func NewListWorkspacesRequest(server string, organizationId string, params *List } + if params.Names != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "names", runtime.ParamLocationQuery, *params.Names); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + if params.Offset != nil { if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { @@ -11321,6 +11939,22 @@ func NewListWorkspaceApiTokensRequest(server string, organizationId string, work queryValues := queryURL.Query() + if params.TokenTypes != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "tokenTypes", runtime.ParamLocationQuery, *params.TokenTypes); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + if params.Offset != nil { if queryFrag, err := runtime.StyleParamWithLocation("form", true, "offset", runtime.ParamLocationQuery, *params.Offset); err != nil { @@ -12640,6 +13274,74 @@ func NewGetSelfUserRepositoryBranchRequest(server string, gitProvider GetSelfUse return req, nil } +// NewGetSelfUserGitAppAuthorizationRequest generates requests for GetSelfUserGitAppAuthorization +func NewGetSelfUserGitAppAuthorizationRequest(server string, gitProvider GetSelfUserGitAppAuthorizationParamsGitProvider) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "gitProvider", runtime.ParamLocationPath, gitProvider) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/users/self/git-providers/%s/authorization", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetSelfUserGitAppInstallationRequest generates requests for GetSelfUserGitAppInstallation +func NewGetSelfUserGitAppInstallationRequest(server string, gitProvider GetSelfUserGitAppInstallationParamsGitProvider) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "gitProvider", runtime.ParamLocationPath, gitProvider) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/users/self/git-providers/%s/installation", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewUpdateSelfUserInviteRequest calls the generic UpdateSelfUserInvite builder with application/json body func NewUpdateSelfUserInviteRequest(server string, inviteId string, body UpdateSelfUserInviteJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader @@ -12887,11 +13589,20 @@ type ClientWithResponsesInterface interface { CreateDeployWithResponse(ctx context.Context, organizationId string, deploymentId string, body CreateDeployJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateDeployResponse, error) + // GetDeploy request + GetDeployWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, params *GetDeployParams, reqEditors ...RequestEditorFn) (*GetDeployResponse, error) + // UpdateDeploy request with any body UpdateDeployWithBodyWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateDeployResponse, error) UpdateDeployWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, body UpdateDeployJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateDeployResponse, error) + // ListDeploySteps request + ListDeployStepsWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, params *ListDeployStepsParams, reqEditors ...RequestEditorFn) (*ListDeployStepsResponse, error) + + // ListDeployStepLogs request + ListDeployStepLogsWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, deployStepId string, params *ListDeployStepLogsParams, reqEditors ...RequestEditorFn) (*ListDeployStepLogsResponse, error) + // GetDeploymentHealth request GetDeploymentHealthWithResponse(ctx context.Context, organizationId string, deploymentId string, reqEditors ...RequestEditorFn) (*GetDeploymentHealthResponse, error) @@ -13101,6 +13812,12 @@ type ClientWithResponsesInterface interface { // GetSelfUserRepositoryBranch request GetSelfUserRepositoryBranchWithResponse(ctx context.Context, gitProvider GetSelfUserRepositoryBranchParamsGitProvider, gitAccount string, gitRepository string, gitBranch string, reqEditors ...RequestEditorFn) (*GetSelfUserRepositoryBranchResponse, error) + // GetSelfUserGitAppAuthorization request + GetSelfUserGitAppAuthorizationWithResponse(ctx context.Context, gitProvider GetSelfUserGitAppAuthorizationParamsGitProvider, reqEditors ...RequestEditorFn) (*GetSelfUserGitAppAuthorizationResponse, error) + + // GetSelfUserGitAppInstallation request + GetSelfUserGitAppInstallationWithResponse(ctx context.Context, gitProvider GetSelfUserGitAppInstallationParamsGitProvider, reqEditors ...RequestEditorFn) (*GetSelfUserGitAppInstallationResponse, error) + // UpdateSelfUserInvite request with any body UpdateSelfUserInviteWithBodyWithResponse(ctx context.Context, inviteId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateSelfUserInviteResponse, error) @@ -14205,6 +14922,33 @@ func (r CreateDeployResponse) StatusCode() int { return 0 } +type GetDeployResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Deploy + JSON400 *Error + JSON401 *Error + JSON403 *Error + JSON404 *Error + JSON500 *Error +} + +// Status returns HTTPResponse.Status +func (r GetDeployResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetDeployResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + type UpdateDeployResponse struct { Body []byte HTTPResponse *http.Response @@ -14216,7 +14960,61 @@ type UpdateDeployResponse struct { } // Status returns HTTPResponse.Status -func (r UpdateDeployResponse) Status() string { +func (r UpdateDeployResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateDeployResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListDeployStepsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DeployStepsPaginated + JSON401 *Error + JSON403 *Error + JSON404 *Error + JSON405 *Error + JSON500 *Error +} + +// Status returns HTTPResponse.Status +func (r ListDeployStepsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListDeployStepsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListDeployStepLogsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DeployStepLogsPaginated + JSON401 *Error + JSON403 *Error + JSON404 *Error + JSON405 *Error + JSON500 *Error +} + +// Status returns HTTPResponse.Status +func (r ListDeployStepLogsResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -14224,7 +15022,7 @@ func (r UpdateDeployResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r UpdateDeployResponse) StatusCode() int { +func (r ListDeployStepLogsResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -15751,6 +16549,60 @@ func (r GetSelfUserRepositoryBranchResponse) StatusCode() int { return 0 } +type GetSelfUserGitAppAuthorizationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *GitApplicationAuthorization + JSON401 *Error + JSON403 *Error + JSON404 *Error + JSON405 *Error + JSON500 *Error +} + +// Status returns HTTPResponse.Status +func (r GetSelfUserGitAppAuthorizationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetSelfUserGitAppAuthorizationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetSelfUserGitAppInstallationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *GitApplicationInstallation + JSON401 *Error + JSON403 *Error + JSON404 *Error + JSON405 *Error + JSON500 *Error +} + +// Status returns HTTPResponse.Status +func (r GetSelfUserGitAppInstallationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetSelfUserGitAppInstallationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + type UpdateSelfUserInviteResponse struct { Body []byte HTTPResponse *http.Response @@ -16283,6 +17135,15 @@ func (c *ClientWithResponses) CreateDeployWithResponse(ctx context.Context, orga return ParseCreateDeployResponse(rsp) } +// GetDeployWithResponse request returning *GetDeployResponse +func (c *ClientWithResponses) GetDeployWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, params *GetDeployParams, reqEditors ...RequestEditorFn) (*GetDeployResponse, error) { + rsp, err := c.GetDeploy(ctx, organizationId, deploymentId, deployId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetDeployResponse(rsp) +} + // UpdateDeployWithBodyWithResponse request with arbitrary body returning *UpdateDeployResponse func (c *ClientWithResponses) UpdateDeployWithBodyWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateDeployResponse, error) { rsp, err := c.UpdateDeployWithBody(ctx, organizationId, deploymentId, deployId, contentType, body, reqEditors...) @@ -16300,6 +17161,24 @@ func (c *ClientWithResponses) UpdateDeployWithResponse(ctx context.Context, orga return ParseUpdateDeployResponse(rsp) } +// ListDeployStepsWithResponse request returning *ListDeployStepsResponse +func (c *ClientWithResponses) ListDeployStepsWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, params *ListDeployStepsParams, reqEditors ...RequestEditorFn) (*ListDeployStepsResponse, error) { + rsp, err := c.ListDeploySteps(ctx, organizationId, deploymentId, deployId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListDeployStepsResponse(rsp) +} + +// ListDeployStepLogsWithResponse request returning *ListDeployStepLogsResponse +func (c *ClientWithResponses) ListDeployStepLogsWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, deployStepId string, params *ListDeployStepLogsParams, reqEditors ...RequestEditorFn) (*ListDeployStepLogsResponse, error) { + rsp, err := c.ListDeployStepLogs(ctx, organizationId, deploymentId, deployId, deployStepId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListDeployStepLogsResponse(rsp) +} + // GetDeploymentHealthWithResponse request returning *GetDeploymentHealthResponse func (c *ClientWithResponses) GetDeploymentHealthWithResponse(ctx context.Context, organizationId string, deploymentId string, reqEditors ...RequestEditorFn) (*GetDeploymentHealthResponse, error) { rsp, err := c.GetDeploymentHealth(ctx, organizationId, deploymentId, reqEditors...) @@ -16965,6 +17844,24 @@ func (c *ClientWithResponses) GetSelfUserRepositoryBranchWithResponse(ctx contex return ParseGetSelfUserRepositoryBranchResponse(rsp) } +// GetSelfUserGitAppAuthorizationWithResponse request returning *GetSelfUserGitAppAuthorizationResponse +func (c *ClientWithResponses) GetSelfUserGitAppAuthorizationWithResponse(ctx context.Context, gitProvider GetSelfUserGitAppAuthorizationParamsGitProvider, reqEditors ...RequestEditorFn) (*GetSelfUserGitAppAuthorizationResponse, error) { + rsp, err := c.GetSelfUserGitAppAuthorization(ctx, gitProvider, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetSelfUserGitAppAuthorizationResponse(rsp) +} + +// GetSelfUserGitAppInstallationWithResponse request returning *GetSelfUserGitAppInstallationResponse +func (c *ClientWithResponses) GetSelfUserGitAppInstallationWithResponse(ctx context.Context, gitProvider GetSelfUserGitAppInstallationParamsGitProvider, reqEditors ...RequestEditorFn) (*GetSelfUserGitAppInstallationResponse, error) { + rsp, err := c.GetSelfUserGitAppInstallation(ctx, gitProvider, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetSelfUserGitAppInstallationResponse(rsp) +} + // UpdateSelfUserInviteWithBodyWithResponse request with arbitrary body returning *UpdateSelfUserInviteResponse func (c *ClientWithResponses) UpdateSelfUserInviteWithBodyWithResponse(ctx context.Context, inviteId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateSelfUserInviteResponse, error) { rsp, err := c.UpdateSelfUserInviteWithBody(ctx, inviteId, contentType, body, reqEditors...) @@ -18771,14 +19668,197 @@ func ParseGetDeploymentResponse(rsp *http.Response) (*GetDeploymentResponse, err return nil, err } - response := &GetDeploymentResponse{ + response := &GetDeploymentResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Deployment + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseUpdateDeploymentResponse parses an HTTP response from a UpdateDeploymentWithResponse call +func ParseUpdateDeploymentResponse(rsp *http.Response) (*UpdateDeploymentResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateDeploymentResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Deployment + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseListDeploymentApiTokensResponse parses an HTTP response from a ListDeploymentApiTokensWithResponse call +func ParseListDeploymentApiTokensResponse(rsp *http.Response) (*ListDeploymentApiTokensResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListDeploymentApiTokensResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ListApiTokensPaginated + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseCreateDeploymentApiTokenResponse parses an HTTP response from a CreateDeploymentApiTokenWithResponse call +func ParseCreateDeploymentApiTokenResponse(rsp *http.Response) (*CreateDeploymentApiTokenResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateDeploymentApiTokenResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Deployment + var dest ApiToken if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -18824,27 +19904,20 @@ func ParseGetDeploymentResponse(rsp *http.Response) (*GetDeploymentResponse, err return response, nil } -// ParseUpdateDeploymentResponse parses an HTTP response from a UpdateDeploymentWithResponse call -func ParseUpdateDeploymentResponse(rsp *http.Response) (*UpdateDeploymentResponse, error) { +// ParseDeleteDeploymentApiTokenResponse parses an HTTP response from a DeleteDeploymentApiTokenWithResponse call +func ParseDeleteDeploymentApiTokenResponse(rsp *http.Response) (*DeleteDeploymentApiTokenResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateDeploymentResponse{ + response := &DeleteDeploymentApiTokenResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Deployment - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -18885,22 +19958,22 @@ func ParseUpdateDeploymentResponse(rsp *http.Response) (*UpdateDeploymentRespons return response, nil } -// ParseListDeploymentApiTokensResponse parses an HTTP response from a ListDeploymentApiTokensWithResponse call -func ParseListDeploymentApiTokensResponse(rsp *http.Response) (*ListDeploymentApiTokensResponse, error) { +// ParseGetDeploymentApiTokenResponse parses an HTTP response from a GetDeploymentApiTokenWithResponse call +func ParseGetDeploymentApiTokenResponse(rsp *http.Response) (*GetDeploymentApiTokenResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListDeploymentApiTokensResponse{ + response := &GetDeploymentApiTokenResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ListApiTokensPaginated + var dest ApiToken if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -18946,15 +20019,15 @@ func ParseListDeploymentApiTokensResponse(rsp *http.Response) (*ListDeploymentAp return response, nil } -// ParseCreateDeploymentApiTokenResponse parses an HTTP response from a CreateDeploymentApiTokenWithResponse call -func ParseCreateDeploymentApiTokenResponse(rsp *http.Response) (*CreateDeploymentApiTokenResponse, error) { +// ParseUpdateDeploymentApiTokenResponse parses an HTTP response from a UpdateDeploymentApiTokenWithResponse call +func ParseUpdateDeploymentApiTokenResponse(rsp *http.Response) (*UpdateDeploymentApiTokenResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateDeploymentApiTokenResponse{ + response := &UpdateDeploymentApiTokenResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -19007,20 +20080,27 @@ func ParseCreateDeploymentApiTokenResponse(rsp *http.Response) (*CreateDeploymen return response, nil } -// ParseDeleteDeploymentApiTokenResponse parses an HTTP response from a DeleteDeploymentApiTokenWithResponse call -func ParseDeleteDeploymentApiTokenResponse(rsp *http.Response) (*DeleteDeploymentApiTokenResponse, error) { +// ParseRotateDeploymentApiTokenResponse parses an HTTP response from a RotateDeploymentApiTokenWithResponse call +func ParseRotateDeploymentApiTokenResponse(rsp *http.Response) (*RotateDeploymentApiTokenResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeleteDeploymentApiTokenResponse{ + response := &RotateDeploymentApiTokenResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ApiToken + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -19061,22 +20141,22 @@ func ParseDeleteDeploymentApiTokenResponse(rsp *http.Response) (*DeleteDeploymen return response, nil } -// ParseGetDeploymentApiTokenResponse parses an HTTP response from a GetDeploymentApiTokenWithResponse call -func ParseGetDeploymentApiTokenResponse(rsp *http.Response) (*GetDeploymentApiTokenResponse, error) { +// ParseDeployRollbackResponse parses an HTTP response from a DeployRollbackWithResponse call +func ParseDeployRollbackResponse(rsp *http.Response) (*DeployRollbackResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetDeploymentApiTokenResponse{ + response := &DeployRollbackResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ApiToken + var dest Deploy if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -19103,13 +20183,6 @@ func ParseGetDeploymentApiTokenResponse(rsp *http.Response) (*GetDeploymentApiTo } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest Error - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -19122,22 +20195,22 @@ func ParseGetDeploymentApiTokenResponse(rsp *http.Response) (*GetDeploymentApiTo return response, nil } -// ParseUpdateDeploymentApiTokenResponse parses an HTTP response from a UpdateDeploymentApiTokenWithResponse call -func ParseUpdateDeploymentApiTokenResponse(rsp *http.Response) (*UpdateDeploymentApiTokenResponse, error) { +// ParseListDeploysResponse parses an HTTP response from a ListDeploysWithResponse call +func ParseListDeploysResponse(rsp *http.Response) (*ListDeploysResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateDeploymentApiTokenResponse{ + response := &ListDeploysResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ApiToken + var dest DeploysPaginated if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -19183,22 +20256,22 @@ func ParseUpdateDeploymentApiTokenResponse(rsp *http.Response) (*UpdateDeploymen return response, nil } -// ParseRotateDeploymentApiTokenResponse parses an HTTP response from a RotateDeploymentApiTokenWithResponse call -func ParseRotateDeploymentApiTokenResponse(rsp *http.Response) (*RotateDeploymentApiTokenResponse, error) { +// ParseCreateDeployResponse parses an HTTP response from a CreateDeployWithResponse call +func ParseCreateDeployResponse(rsp *http.Response) (*CreateDeployResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &RotateDeploymentApiTokenResponse{ + response := &CreateDeployResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest ApiToken + var dest Deploy if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -19244,15 +20317,15 @@ func ParseRotateDeploymentApiTokenResponse(rsp *http.Response) (*RotateDeploymen return response, nil } -// ParseDeployRollbackResponse parses an HTTP response from a DeployRollbackWithResponse call -func ParseDeployRollbackResponse(rsp *http.Response) (*DeployRollbackResponse, error) { +// ParseGetDeployResponse parses an HTTP response from a GetDeployWithResponse call +func ParseGetDeployResponse(rsp *http.Response) (*GetDeployResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &DeployRollbackResponse{ + response := &GetDeployResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -19286,6 +20359,13 @@ func ParseDeployRollbackResponse(rsp *http.Response) (*DeployRollbackResponse, e } response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -19298,22 +20378,22 @@ func ParseDeployRollbackResponse(rsp *http.Response) (*DeployRollbackResponse, e return response, nil } -// ParseListDeploysResponse parses an HTTP response from a ListDeploysWithResponse call -func ParseListDeploysResponse(rsp *http.Response) (*ListDeploysResponse, error) { +// ParseUpdateDeployResponse parses an HTTP response from a UpdateDeployWithResponse call +func ParseUpdateDeployResponse(rsp *http.Response) (*UpdateDeployResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &ListDeploysResponse{ + response := &UpdateDeployResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest DeploysPaginated + var dest Deploy if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -19340,13 +20420,6 @@ func ParseListDeploysResponse(rsp *http.Response) (*ListDeploysResponse, error) } response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: - var dest Error - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON404 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -19359,34 +20432,27 @@ func ParseListDeploysResponse(rsp *http.Response) (*ListDeploysResponse, error) return response, nil } -// ParseCreateDeployResponse parses an HTTP response from a CreateDeployWithResponse call -func ParseCreateDeployResponse(rsp *http.Response) (*CreateDeployResponse, error) { +// ParseListDeployStepsResponse parses an HTTP response from a ListDeployStepsWithResponse call +func ParseListDeployStepsResponse(rsp *http.Response) (*ListDeployStepsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &CreateDeployResponse{ + response := &ListDeployStepsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Deploy + var dest DeployStepsPaginated if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest Error - if err := json.Unmarshal(bodyBytes, &dest); err != nil { - return nil, err - } - response.JSON400 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -19408,6 +20474,13 @@ func ParseCreateDeployResponse(rsp *http.Response) (*CreateDeployResponse, error } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 405: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON405 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -19420,47 +20493,54 @@ func ParseCreateDeployResponse(rsp *http.Response) (*CreateDeployResponse, error return response, nil } -// ParseUpdateDeployResponse parses an HTTP response from a UpdateDeployWithResponse call -func ParseUpdateDeployResponse(rsp *http.Response) (*UpdateDeployResponse, error) { +// ParseListDeployStepLogsResponse parses an HTTP response from a ListDeployStepLogsWithResponse call +func ParseListDeployStepLogsResponse(rsp *http.Response) (*ListDeployStepLogsResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &UpdateDeployResponse{ + response := &ListDeployStepLogsResponse{ Body: bodyBytes, HTTPResponse: rsp, } switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: - var dest Deploy + var dest DeployStepLogsPaginated if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON400 = &dest + response.JSON401 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON401 = &dest + response.JSON403 = &dest - case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: var dest Error if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } - response.JSON403 = &dest + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 405: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON405 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest Error @@ -22818,6 +23898,128 @@ func ParseGetSelfUserRepositoryBranchResponse(rsp *http.Response) (*GetSelfUserR return response, nil } +// ParseGetSelfUserGitAppAuthorizationResponse parses an HTTP response from a GetSelfUserGitAppAuthorizationWithResponse call +func ParseGetSelfUserGitAppAuthorizationResponse(rsp *http.Response) (*GetSelfUserGitAppAuthorizationResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetSelfUserGitAppAuthorizationResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest GitApplicationAuthorization + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 405: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON405 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseGetSelfUserGitAppInstallationResponse parses an HTTP response from a GetSelfUserGitAppInstallationWithResponse call +func ParseGetSelfUserGitAppInstallationResponse(rsp *http.Response) (*GetSelfUserGitAppInstallationResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetSelfUserGitAppInstallationResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest GitApplicationInstallation + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 405: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON405 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + // ParseUpdateSelfUserInviteResponse parses an HTTP response from a UpdateSelfUserInviteWithResponse call func ParseUpdateSelfUserInviteResponse(rsp *http.Response) (*UpdateSelfUserInviteResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index 045b8520e..8a6f53513 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -42,8 +42,8 @@ const ( ) // List all deployment Tokens -func ListTokens(client astrocore.CoreClient, deployment string, out io.Writer) error { - apiTokens, err := getDeploymentTokens(deployment, client) +func ListTokens(client astrocore.CoreClient, deployment string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, out io.Writer) error { + apiTokens, err := getDeploymentTokens(deployment, tokenTypes, client) if err != nil { return err } @@ -119,9 +119,11 @@ func UpdateToken(id, name, newName, description, role, deployment string, out io if err != nil { return err } - + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ + "DEPLOYMENT", + } organization := ctx.Organization - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) if err != nil { return err } @@ -172,9 +174,11 @@ func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Wr if err != nil { return err } - + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ + "DEPLOYMENT", + } organization := ctx.Organization - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) if err != nil { return err } @@ -218,7 +222,12 @@ func DeleteToken(id, name, deployment string, force bool, out io.Writer, client } organization := ctx.Organization - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ + "DEPLOYMENT", + } + + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) if err != nil { return err } @@ -295,13 +304,13 @@ func selectTokens(deployment string, apiTokens []astrocore.ApiToken) (astrocore. } // get all deployment tokens -func getDeploymentTokens(deployment string, client astrocore.CoreClient) ([]astrocore.ApiToken, error) { +func getDeploymentTokens(deployment string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, client astrocore.CoreClient) ([]astrocore.ApiToken, error) { ctx, err := context.GetCurrentContext() if err != nil { return []astrocore.ApiToken{}, err } - resp, err := client.ListDeploymentApiTokensWithResponse(httpContext.Background(), ctx.Organization, deployment, &astrocore.ListDeploymentApiTokensParams{}) + resp, err := client.ListDeploymentApiTokensWithResponse(httpContext.Background(), ctx.Organization, deployment, &astrocore.ListDeploymentApiTokensParams{TokenTypes: tokenTypes}) if err != nil { return []astrocore.ApiToken{}, err } @@ -385,9 +394,9 @@ func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astro return *resp.JSON200, nil } -func GetDeploymentTokenFromInputOrUser(id, name, deployment, organization string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func GetDeploymentTokenFromInputOrUser(id, name, deployment, organization string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { if id == "" { - tokens, err := getDeploymentTokens(deployment, client) + tokens, err := getDeploymentTokens(deployment, tokenTypes, client) if err != nil { return token, err } @@ -415,7 +424,10 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl return err } organization := ctx.Organization - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ + "ORGANIZATION", + } + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) if err != nil { return err } @@ -482,8 +494,10 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace string, deployment s if workspace == "" { workspace = ctx.Workspace } - - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, client, iamClient) + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ + "WORKSPACE", + } + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) if err != nil { return err } diff --git a/cloud/workspace/workspace_token.go b/cloud/workspace/workspace_token.go index 6e81d66be..cc7fb2cbe 100644 --- a/cloud/workspace/workspace_token.go +++ b/cloud/workspace/workspace_token.go @@ -54,7 +54,7 @@ func ListTokens(client astrocore.CoreClient, workspace string, out io.Writer) er workspace = ctx.Workspace } - apiTokens, err := getWorkspaceTokens(workspace, client) + apiTokens, err := getWorkspaceTokens(workspace, nil, client) if err != nil { return err } @@ -142,7 +142,9 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. organization := ctx.Organization - token, err := GetTokenFromInputOrUser(id, name, workspace, organization, client, iamClient) + tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} + + token, err := GetTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) if err != nil { return err } @@ -226,7 +228,9 @@ func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Wri workspace = ctx.Workspace } organization := ctx.Organization - token, err := GetTokenFromInputOrUser(id, name, workspace, organization, client, iamClient) + tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} + + token, err := GetTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) if err != nil { return err } @@ -272,7 +276,7 @@ func DeleteToken(id, name, workspace string, force bool, out io.Writer, client a workspace = ctx.Workspace } organization := ctx.Organization - token, err := GetTokenFromInputOrUser(id, name, workspace, organization, client, iamClient) + token, err := GetTokenFromInputOrUser(id, name, workspace, organization, nil, client, iamClient) if err != nil { return err } @@ -364,7 +368,7 @@ func selectTokens(workspace string, apiTokens []astrocore.ApiToken) (astrocore.A } // get all workspace tokens -func getWorkspaceTokens(workspace string, client astrocore.CoreClient) ([]astrocore.ApiToken, error) { +func getWorkspaceTokens(workspace string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient) ([]astrocore.ApiToken, error) { ctx, err := context.GetCurrentContext() if err != nil { return []astrocore.ApiToken{}, err @@ -373,7 +377,7 @@ func getWorkspaceTokens(workspace string, client astrocore.CoreClient) ([]astroc workspace = ctx.Workspace } - resp, err := client.ListWorkspaceApiTokensWithResponse(httpContext.Background(), ctx.Organization, workspace, &astrocore.ListWorkspaceApiTokensParams{}) + resp, err := client.ListWorkspaceApiTokensWithResponse(httpContext.Background(), ctx.Organization, workspace, &astrocore.ListWorkspaceApiTokensParams{TokenTypes: tokenTypes}) if err != nil { return []astrocore.ApiToken{}, err } @@ -457,9 +461,9 @@ func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astro return *resp.JSON200, nil } -func GetTokenFromInputOrUser(id, name, workspace, organization string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func GetTokenFromInputOrUser(id, name, workspace, organization string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { if id == "" { - tokens, err := getWorkspaceTokens(workspace, client) + tokens, err := getWorkspaceTokens(workspace, tokenTypes, client) if err != nil { return token, err } @@ -492,7 +496,9 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace string, deploy workspace = ctx.Workspace } - token, err := GetTokenFromInputOrUser(id, name, workspace, organization, client, iamClient) + tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} + + token, err := GetTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) if err != nil { return err } diff --git a/cmd/cloud/deployment.go b/cmd/cloud/deployment.go index c921dbbf3..1aa0670ac 100644 --- a/cmd/cloud/deployment.go +++ b/cmd/cloud/deployment.go @@ -1043,6 +1043,7 @@ func newOrgTokenManageCmd(out io.Writer) *cobra.Command { cmd.AddCommand( newUpsertOrganizationTokenDeploymentRole(out), newRemoveOrganizationTokenDeploymentRole(out), + newListOrganizationTokensInDeployment(out), ) return cmd } @@ -1058,6 +1059,7 @@ func newWorkspaceTokenManageCmd(out io.Writer) *cobra.Command { cmd.AddCommand( newUpsertWorkspaceTokenDeploymentRole(out), newRemoveWorkspaceTokenDeploymentRole(out), + newListWorkspaceTokensInDeployment(out), ) return cmd } @@ -1183,12 +1185,62 @@ func removeWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out i return deployment.RemoveWorkspaceTokenDeploymentRole(workspaceTokenID, orgTokenName, workspaceID, deploymentID, out, astroCoreClient, astroCoreIamClient) } +func newListOrganizationTokensInDeployment(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "list", + Short: "List all Organization API tokens in a deployment", + Long: "List all Organization API tokens in a deployment\n$astro deployment token organization-token list", + RunE: func(cmd *cobra.Command, args []string) error { + return listOrganizationTokensInDeployment(cmd, args, out) + }, + } + return cmd +} + +func newListWorkspaceTokensInDeployment(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "list", + Short: "List all Workspace API tokens in a deployment", + Long: "List all Workspace API tokens in a deployment\n$astro deployment token workspace-token list", + RunE: func(cmd *cobra.Command, args []string) error { + return listWorkspaceTokensInDeployment(cmd, args, out) + }, + } + return cmd +} + +func listOrganizationTokensInDeployment(cmd *cobra.Command, args []string, out io.Writer) error { + if deploymentID == "" { + return errors.New("flag --deployment-id is required") + } + // if an id was provided in the args we use it + + cmd.SilenceUsage = true + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ + "ORGANIZATION", + } + return deployment.ListTokens(astroCoreClient, deploymentID, &tokenTypes, out) +} + +func listWorkspaceTokensInDeployment(cmd *cobra.Command, args []string, out io.Writer) error { + if deploymentID == "" { + return errors.New("flag --deployment-id is required") + } + // if an id was provided in the args we use it + + cmd.SilenceUsage = true + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ + "WORKSPACE", + } + return deployment.ListTokens(astroCoreClient, deploymentID, &tokenTypes, out) +} + func listDeploymentToken(cmd *cobra.Command, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } cmd.SilenceUsage = true - return deployment.ListTokens(astroCoreClient, deploymentID, out) + return deployment.ListTokens(astroCoreClient, deploymentID, nil, out) } func createDeploymentToken(cmd *cobra.Command, out io.Writer) error { From d15bff647f896149d97e77189aed7698d8ed6741 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 10:50:36 -0400 Subject: [PATCH 06/26] add workspace token mgmt cmds for managing org tokens in workspaces --- cloud/deployment/deployment_token.go | 2 +- cloud/organization/organization_token.go | 75 ++++++++++++++++++ cloud/workspace/workspace_token.go | 98 +++++++++++++++++++++++- cmd/cloud/workspace.go | 94 ++++++++++++++++++++++- 4 files changed, 265 insertions(+), 4 deletions(-) diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index 8a6f53513..e5b549818 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -400,7 +400,7 @@ func GetDeploymentTokenFromInputOrUser(id, name, deployment, organization string if err != nil { return token, err } - tokenFromList, err := getDeploymentToken(id, name, deployment, "\nPlease select the Organization API token you would like to remove from the Deployment:", tokens) + tokenFromList, err := getDeploymentToken(id, name, deployment, "\nPlease select the Organization API token you would like to update:", tokens) if err != nil { return token, err diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index 68b495286..9455146ed 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -198,6 +198,81 @@ func UpsertOrgTokenDeploymentRole(id, name, role, deployment string, out io.Writ return nil } +func UpsertOrgTokenWorkspaceRole(id, name, role, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { + ctx, err := context.GetCurrentContext() + if err != nil { + return err + } + + if workspace == "" { + workspace = ctx.Workspace + } + + token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) + if err != nil { + return err + } + apiTokenID := token.Id + var orgRole string + apiTokenWorkspaceRole := astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: workspace, + Role: role, + } + apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} + + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} + roles := *token.Roles + for i := range roles { + if roles[i].EntityId == workspace { + if roles[i].Role == role { + return errOrgTokenInDeployment + } else { + continue + } + } + + if roles[i].EntityId == ctx.Organization { + orgRole = roles[i].Role + } + + if roles[i].EntityType == workspaceEntity { + apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + + if roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + } + + updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ + Organization: orgRole, + Deployment: &apiTokenDeploymentRoles, + Workspace: &apiTokenWorkspaceRoles, + } + updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ + Name: token.Name, + Description: token.Description, + Roles: updateOrganizationAPITokenRoles, + } + + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) + if err != nil { + return err + } + err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return err + } + fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Workspace\n", token.Name) + return nil +} + func selectTokens(apiTokens []astrocore.ApiToken) (astrocore.ApiToken, error) { apiTokensMap := map[string]astrocore.ApiToken{} tab := newTokenSelectionTableOut() diff --git a/cloud/workspace/workspace_token.go b/cloud/workspace/workspace_token.go index cc7fb2cbe..2198e5e53 100644 --- a/cloud/workspace/workspace_token.go +++ b/cloud/workspace/workspace_token.go @@ -44,7 +44,7 @@ const ( ) // List all workspace Tokens -func ListTokens(client astrocore.CoreClient, workspace string, out io.Writer) error { +func ListTokens(client astrocore.CoreClient, workspace string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, out io.Writer) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -54,7 +54,7 @@ func ListTokens(client astrocore.CoreClient, workspace string, out io.Writer) er workspace = ctx.Workspace } - apiTokens, err := getWorkspaceTokens(workspace, nil, client) + apiTokens, err := getWorkspaceTokens(workspace, tokenTypes, client) if err != nil { return err } @@ -552,3 +552,97 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace string, deploy fmt.Fprintf(out, "Astro Workspace API token %s was successfully added to the Deployment\n", token.Name) return nil } + +func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { + ctx, err := context.GetCurrentContext() + if err != nil { + return err + } + + if workspace == "" { + workspace = ctx.Workspace + } + + organization := ctx.Organization + tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{ + "ORGANIZATION", + } + token, err := GetWorkspaceTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) + if err != nil { + return err + } + roles := *token.Roles + + apiTokenID := token.Id + var orgRole string + apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} + for i := range roles { + if roles[i].EntityId == workspace { + continue // this removes the role in question + } + + if roles[i].EntityId == ctx.Organization { + orgRole = roles[i].Role + } + + if roles[i].EntityType == workspaceEntity { + apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + + if roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + } + + updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ + Organization: orgRole, + Deployment: &apiTokenDeploymentRoles, + Workspace: &apiTokenWorkspaceRoles, + } + updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ + Name: token.Name, + Description: token.Description, + Roles: updateOrganizationAPITokenRoles, + } + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) + if err != nil { + return err + } + err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return err + } + fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) + return nil +} + +func GetWorkspaceTokenFromInputOrUser(id, name, workspace, organization string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { + if id == "" { + tokens, err := getWorkspaceTokens(workspace, tokenTypes, client) + if err != nil { + return token, err + } + tokenFromList, err := getWorkspaceToken(id, name, workspace, "\nPlease select the Organization API token you would like to update:", tokens) + + if err != nil { + return token, err + } + token, err = getTokenByID(tokenFromList.Id, organization, iamClient) + if err != nil { + return token, err + } + } else { + token, err = getTokenByID(id, organization, iamClient) + if err != nil { + return token, err + } + } + return token, err +} diff --git a/cmd/cloud/workspace.go b/cmd/cloud/workspace.go index 25ff9aaa8..6fa1c3faa 100644 --- a/cmd/cloud/workspace.go +++ b/cmd/cloud/workspace.go @@ -2,6 +2,7 @@ package cloud import ( "fmt" + astrocore "github.com/astronomer/astro-cli/astro-client-core" "io" "os" "strconv" @@ -232,6 +233,7 @@ func newWorkspaceTokenRootCmd(out io.Writer) *cobra.Command { newWorkspaceTokenRotateCmd(out), newWorkspaceTokenDeleteCmd(out), newWorkspaceTokenAddOrgTokenCmd(out), + newWorkspaceOrgTokenManageCmd(out), ) cmd.PersistentFlags().StringVar(&workspaceID, "workspace-id", "", "workspace where you would like to manage tokens") return cmd @@ -373,6 +375,96 @@ func newWorkspaceTokenAddOrgTokenCmd(out io.Writer) *cobra.Command { return cmd } +//nolint:dupl +func newWorkspaceOrgTokenManageCmd(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "organization-token", + Short: "Manage organization tokens in a workspace", + Long: "Manage organization tokens in a workspace", + } + cmd.SetOut(out) + cmd.AddCommand( + newUpsertOrganizationTokenWorkspaceRole(out), + newRemoveOrganizationTokenWorkspaceRole(out), + newListOrganizationTokensInWorkspace(out), + ) + return cmd +} + +func newUpsertOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "upsert [ORG_TOKEN_ID]", + Short: "Upsert an Organization API token's Workspace Role", + Long: "Upsert an Organization API token's Workspace Role\n$astro workspace token organization-token upsert [ORG_TOKEN_ID] --name [token name] --role [" + allowedWorkspaceRoleNames + "].", + RunE: func(cmd *cobra.Command, args []string) error { + return upsertOrgTokenToWorkspaceRole(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to add to a Workspace. If the name contains a space, specify the entire name within quotes \"\" ") + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Workspace role to grant to the "+ + "Organization API token. Possible values are"+allowedWorkspaceRoleNamesProse) + return cmd +} + +func upsertOrgTokenToWorkspaceRole(cmd *cobra.Command, args []string, out io.Writer) error { + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + orgTokenID = strings.ToLower(args[0]) + } + if tokenRole == "" { + // no role was provided so ask the user for it + tokenRole = input.Text("Enter a role for the new Workspace API token. Possible values are " + allowedWorkspaceRoleNamesProse + ": ") + } + cmd.SilenceUsage = true + + return organization.UpsertOrgTokenWorkspaceRole(orgTokenID, orgTokenName, tokenRole, workspaceID, out, astroCoreClient, astroCoreIamClient) +} + +func newRemoveOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "remove [ORG_TOKEN_ID]", + Short: "Remove an Workspace API token's Deployment Role", + Long: "Remove an Workspace API token's Deployment Role\n$astro workspace token organization-token remove [ORG_TOKEN_ID] --name [token name].", + RunE: func(cmd *cobra.Command, args []string) error { + return removeWorkspaceTokenFromDeploymentRole(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Workspace API token you want to remove from a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") + return cmd +} + +func removeWorkspaceTokenFromDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + orgTokenID = strings.ToLower(args[0]) + } + + cmd.SilenceUsage = true + return workspace.RemoveOrgTokenWorkspaceRole(orgTokenID, orgTokenName, workspaceID, out, astroCoreClient, astroCoreIamClient) +} + +func newListOrganizationTokensInWorkspace(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "list", + Short: "List all Organization API tokens in a workspace", + Long: "List all Organization API tokens in a workspace\n$astro workspace token organization-token list", + RunE: func(cmd *cobra.Command, args []string) error { + return listOrganizationTokensInWorkspace(cmd, args, out) + }, + } + return cmd +} + +func listOrganizationTokensInWorkspace(cmd *cobra.Command, args []string, out io.Writer) error { + cmd.SilenceUsage = true + tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{ + "ORGANIZATION", + } + return workspace.ListTokens(astroCoreClient, deploymentID, &tokenTypes, out) +} + func newWorkspaceTeamRemoveCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "remove", @@ -559,7 +651,7 @@ func removeWorkspaceUser(cmd *cobra.Command, args []string, out io.Writer) error func listWorkspaceToken(cmd *cobra.Command, out io.Writer) error { cmd.SilenceUsage = true - return workspace.ListTokens(astroCoreClient, workspaceID, out) + return workspace.ListTokens(astroCoreClient, workspaceID, nil, out) } func createWorkspaceToken(cmd *cobra.Command, out io.Writer) error { From 2d57c4eee5c5eef94c17dfc36450188cbab5459e Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 11:47:17 -0400 Subject: [PATCH 07/26] remove cyclic import error --- cloud/deployment/deployment_token.go | 162 +++++++++++++++++- cloud/organization/organization_token.go | 145 ---------------- .../workspace_token.go | 156 +++++++++-------- .../workspace_token_test.go | 13 +- cmd/cloud/deployment.go | 102 +++++++++-- cmd/cloud/workspace.go | 62 +++++-- 6 files changed, 386 insertions(+), 254 deletions(-) rename cloud/{workspace => workspace-token}/workspace_token.go (89%) rename cloud/{workspace => workspace-token}/workspace_token_test.go (98%) diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index e5b549818..d0f685188 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" + "github.com/astronomer/astro-cli/cloud/organization" + workspace2 "github.com/astronomer/astro-cli/cloud/workspace-token" "io" "os" "strconv" @@ -32,8 +34,10 @@ func newTokenSelectionTableOut() *printutil.Table { } var ( - errInvalidDeploymentTokenKey = errors.New("invalid Deployment API token selection") - ErrDeploymentTokenNotFound = errors.New("no Deployment API token was found for the API token name you provided") + errInvalidDeploymentTokenKey = errors.New("invalid Deployment API token selection") + ErrDeploymentTokenNotFound = errors.New("no Deployment API token was found for the API token name you provided") + errWorkspaceTokenInDeployment = errors.New("this Workspace API token has already been added to the Deployment with that role") + errOrgTokenInDeployment = errors.New("this Organization API token has already been added to the Deployment with that role") ) const ( @@ -544,3 +548,157 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace string, deployment s fmt.Fprintf(out, "Astro Workspace API token %s was successfully added to the Deployment\n", token.Name) return nil } + +func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, operation string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { + ctx, err := context.GetCurrentContext() + if err != nil { + return err + } + + organization := ctx.Organization + + if workspace == "" { + workspace = ctx.Workspace + } + + var token astrocoreiam.ApiToken + if operation == "create" { + tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} + token, err = workspace2.GetTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) + if err != nil { + return err + } + } else { + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{"WORKSPACE"} + token, err = GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) + } + + apiTokenID := token.Id + var workspaceRole string + apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: deployment, + Role: role, + } + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} + + for i := range *token.Roles { + roles := *token.Roles + if roles[i].EntityId == deployment { + if roles[i].Role == role { + return errWorkspaceTokenInDeployment + } else { + continue + } + } + + if roles[i].EntityId == ctx.Workspace { + workspaceRole = roles[i].Role + } + + if roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + } + updateWorkspaceAPITokenRoles := astrocore.UpdateWorkspaceApiTokenRolesRequest{ + Deployment: &apiTokenDeploymentRoles, + Workspace: &workspaceRole, + } + updateWorkspaceAPITokenRequest := astrocore.UpdateWorkspaceApiTokenRequest{ + Name: token.Name, + Description: token.Description, + Roles: &updateWorkspaceAPITokenRoles, + } + + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID, updateWorkspaceAPITokenRequest) + if err != nil { + return err + } + err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return err + } + fmt.Fprintf(out, "Astro Workspace API token %s was successfully added to the Deployment\n", token.Name) + return nil +} + +func UpsertOrgTokenDeploymentRole(id, name, role, deployment, operation string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { + ctx, err := context.GetCurrentContext() + if err != nil { + return err + } + var token astrocoreiam.ApiToken + if operation == "create" { + token, err = organization.GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) + if err != nil { + return err + } + } else { + tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{"ORGANIZATION"} + token, err = GetDeploymentTokenFromInputOrUser(id, name, deployment, ctx.Organization, &tokenTypes, client, iamClient) + if err != nil { + return err + } + } + + apiTokenID := token.Id + var orgRole string + apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} + apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: deployment, + Role: role, + } + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} + roles := *token.Roles + for i := range roles { + if roles[i].EntityId == deployment { + if roles[i].Role == role { + return errOrgTokenInDeployment + } else { + continue + } + } + + if roles[i].EntityId == ctx.Organization { + orgRole = roles[i].Role + } + + if roles[i].EntityType == workspaceEntity { + apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + + if roles[i].EntityType == deploymentEntity { + apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) + } + } + + updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ + Organization: orgRole, + Deployment: &apiTokenDeploymentRoles, + Workspace: &apiTokenWorkspaceRoles, + } + updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ + Name: token.Name, + Description: token.Description, + Roles: updateOrganizationAPITokenRoles, + } + + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) + if err != nil { + return err + } + err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) + if err != nil { + return err + } + fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) + return nil +} diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index 9455146ed..2abf57441 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -128,151 +128,6 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli return nil } -func UpsertOrgTokenDeploymentRole(id, name, role, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { - ctx, err := context.GetCurrentContext() - if err != nil { - return err - } - - token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) - if err != nil { - return err - } - apiTokenID := token.Id - var orgRole string - apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} - apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: deployment, - Role: role, - } - apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} - roles := *token.Roles - for i := range roles { - if roles[i].EntityId == deployment { - if roles[i].Role == role { - return errOrgTokenInDeployment - } else { - continue - } - } - - if roles[i].EntityId == ctx.Organization { - orgRole = roles[i].Role - } - - if roles[i].EntityType == workspaceEntity { - apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: roles[i].EntityId, - Role: roles[i].Role, - }) - } - - if roles[i].EntityType == deploymentEntity { - apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: roles[i].EntityId, - Role: roles[i].Role, - }) - } - } - - updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ - Organization: orgRole, - Deployment: &apiTokenDeploymentRoles, - Workspace: &apiTokenWorkspaceRoles, - } - updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ - Name: token.Name, - Description: token.Description, - Roles: updateOrganizationAPITokenRoles, - } - - resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) - if err != nil { - return err - } - err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) - if err != nil { - return err - } - fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) - return nil -} - -func UpsertOrgTokenWorkspaceRole(id, name, role, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { - ctx, err := context.GetCurrentContext() - if err != nil { - return err - } - - if workspace == "" { - workspace = ctx.Workspace - } - - token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) - if err != nil { - return err - } - apiTokenID := token.Id - var orgRole string - apiTokenWorkspaceRole := astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: workspace, - Role: role, - } - apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} - - apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} - roles := *token.Roles - for i := range roles { - if roles[i].EntityId == workspace { - if roles[i].Role == role { - return errOrgTokenInDeployment - } else { - continue - } - } - - if roles[i].EntityId == ctx.Organization { - orgRole = roles[i].Role - } - - if roles[i].EntityType == workspaceEntity { - apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: roles[i].EntityId, - Role: roles[i].Role, - }) - } - - if roles[i].EntityType == deploymentEntity { - apiTokenDeploymentRoles = append(apiTokenDeploymentRoles, astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: roles[i].EntityId, - Role: roles[i].Role, - }) - } - } - - updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ - Organization: orgRole, - Deployment: &apiTokenDeploymentRoles, - Workspace: &apiTokenWorkspaceRoles, - } - updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ - Name: token.Name, - Description: token.Description, - Roles: updateOrganizationAPITokenRoles, - } - - resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) - if err != nil { - return err - } - err = astrocore.NormalizeAPIError(resp.HTTPResponse, resp.Body) - if err != nil { - return err - } - fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Workspace\n", token.Name) - return nil -} - func selectTokens(apiTokens []astrocore.ApiToken) (astrocore.ApiToken, error) { apiTokensMap := map[string]astrocore.ApiToken{} tab := newTokenSelectionTableOut() diff --git a/cloud/workspace/workspace_token.go b/cloud/workspace-token/workspace_token.go similarity index 89% rename from cloud/workspace/workspace_token.go rename to cloud/workspace-token/workspace_token.go index 2198e5e53..41dc1134e 100644 --- a/cloud/workspace/workspace_token.go +++ b/cloud/workspace-token/workspace_token.go @@ -1,9 +1,11 @@ -package workspace +package workspace_token import ( httpContext "context" "errors" "fmt" + "github.com/astronomer/astro-cli/cloud/organization" + workspace2 "github.com/astronomer/astro-cli/cloud/workspace" "io" "os" "strconv" @@ -36,6 +38,7 @@ var ( errInvalidWorkspaceTokenKey = errors.New("invalid Workspace API token selection") errWorkspaceTokenInDeployment = errors.New("this Workspace API token has already been added to the Deployment with that role") ErrWorkspaceTokenNotFound = errors.New("no Workspace API token was found for the API token name you provided") + errOrgTokenInWorkspace = errors.New("this Organization API token has already been added to the Workspace with that role") ) const ( @@ -93,7 +96,7 @@ func CreateToken(name, description, role, workspace string, expiration int, clea return err } if name == "" { - return ErrInvalidTokenName + return workspace2.ErrInvalidTokenName } ctx, err := context.GetCurrentContext() if err != nil { @@ -484,44 +487,44 @@ func GetTokenFromInputOrUser(id, name, workspace, organization string, tokenType return token, err } -func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace string, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - organization := ctx.Organization - if workspace == "" { workspace = ctx.Workspace } - tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} - - token, err := GetTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) + organization := ctx.Organization + tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{ + "ORGANIZATION", + } + token, err := GetWorkspaceTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) if err != nil { return err } + roles := *token.Roles + apiTokenID := token.Id - var workspaceRole string - apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: deployment, - Role: role, - } - apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} + var orgRole string + apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} + for i := range roles { + if roles[i].EntityId == workspace { + continue // this removes the role in question + } - for i := range *token.Roles { - roles := *token.Roles - if roles[i].EntityId == deployment { - if roles[i].Role == role { - return errWorkspaceTokenInDeployment - } else { - continue - } + if roles[i].EntityId == ctx.Organization { + orgRole = roles[i].Role } - if roles[i].EntityId == ctx.Workspace { - workspaceRole = roles[i].Role + if roles[i].EntityType == workspaceEntity { + apiTokenWorkspaceRoles = append(apiTokenWorkspaceRoles, astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: roles[i].EntityId, + Role: roles[i].Role, + }) } if roles[i].EntityType == deploymentEntity { @@ -531,17 +534,18 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace string, deploy }) } } - updateWorkspaceAPITokenRoles := astrocore.UpdateWorkspaceApiTokenRolesRequest{ - Deployment: &apiTokenDeploymentRoles, - Workspace: &workspaceRole, + + updateOrganizationAPITokenRoles := astrocore.UpdateOrganizationApiTokenRolesRequest{ + Organization: orgRole, + Deployment: &apiTokenDeploymentRoles, + Workspace: &apiTokenWorkspaceRoles, } - updateWorkspaceAPITokenRequest := astrocore.UpdateWorkspaceApiTokenRequest{ + updateOrganizationAPITokenRequest := astrocore.UpdateOrganizationApiTokenRequest{ Name: token.Name, Description: token.Description, - Roles: &updateWorkspaceAPITokenRoles, + Roles: updateOrganizationAPITokenRoles, } - - resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID, updateWorkspaceAPITokenRequest) + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) if err != nil { return err } @@ -549,11 +553,35 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace string, deploy if err != nil { return err } - fmt.Fprintf(out, "Astro Workspace API token %s was successfully added to the Deployment\n", token.Name) + fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) return nil } -func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func GetWorkspaceTokenFromInputOrUser(id, name, workspace, organization string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { + if id == "" { + tokens, err := getWorkspaceTokens(workspace, tokenTypes, client) + if err != nil { + return token, err + } + tokenFromList, err := getWorkspaceToken(id, name, workspace, "\nPlease select the Organization API token you would like to update:", tokens) + + if err != nil { + return token, err + } + token, err = getTokenByID(tokenFromList.Id, organization, iamClient) + if err != nil { + return token, err + } + } else { + token, err = getTokenByID(id, organization, iamClient) + if err != nil { + return token, err + } + } + return token, err +} + +func UpsertOrgTokenWorkspaceRole(id, name, role, workspace, operation string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -562,24 +590,37 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie if workspace == "" { workspace = ctx.Workspace } - - organization := ctx.Organization - tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{ - "ORGANIZATION", - } - token, err := GetWorkspaceTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) - if err != nil { - return err + var token astrocoreiam.ApiToken + if operation == "create" { + token, err = organization.GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) + if err != nil { + return err + } + } else { + tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"ORGANIZATION"} + token, err = GetTokenFromInputOrUser(id, name, workspace, ctx.Organization, &tokenTypes, client, iamClient) + if err != nil { + return err + } } - roles := *token.Roles apiTokenID := token.Id var orgRole string - apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} + apiTokenWorkspaceRole := astrocore.ApiTokenWorkspaceRoleRequest{ + EntityId: workspace, + Role: role, + } + apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} + apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} + roles := *token.Roles for i := range roles { if roles[i].EntityId == workspace { - continue // this removes the role in question + if roles[i].Role == role { + return errOrgTokenInWorkspace + } else { + continue + } } if roles[i].EntityId == ctx.Organization { @@ -611,6 +652,7 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie Description: token.Description, Roles: updateOrganizationAPITokenRoles, } + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) if err != nil { return err @@ -619,30 +661,6 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie if err != nil { return err } - fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) + fmt.Fprintf(out, "Astro Organization API token %s was successfully added/updated to the Workspace\n", token.Name) return nil } - -func GetWorkspaceTokenFromInputOrUser(id, name, workspace, organization string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { - if id == "" { - tokens, err := getWorkspaceTokens(workspace, tokenTypes, client) - if err != nil { - return token, err - } - tokenFromList, err := getWorkspaceToken(id, name, workspace, "\nPlease select the Organization API token you would like to update:", tokens) - - if err != nil { - return token, err - } - token, err = getTokenByID(tokenFromList.Id, organization, iamClient) - if err != nil { - return token, err - } - } else { - token, err = getTokenByID(id, organization, iamClient) - if err != nil { - return token, err - } - } - return token, err -} diff --git a/cloud/workspace/workspace_token_test.go b/cloud/workspace-token/workspace_token_test.go similarity index 98% rename from cloud/workspace/workspace_token_test.go rename to cloud/workspace-token/workspace_token_test.go index a5ce08aea..a47e31e9a 100644 --- a/cloud/workspace/workspace_token_test.go +++ b/cloud/workspace-token/workspace_token_test.go @@ -1,8 +1,9 @@ -package workspace +package workspace_token import ( "bytes" "encoding/json" + "github.com/astronomer/astro-cli/cloud/workspace" "net/http" "os" "testing" @@ -88,7 +89,7 @@ var ( HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: errorBodyCreate, + Body: workspace.errorBodyCreate, JSON200: nil, } UpdateWorkspaceAPITokenResponseOK = astrocore.UpdateWorkspaceApiTokenResponse{ @@ -101,7 +102,7 @@ var ( HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: errorBodyUpdate, + Body: workspace.errorBodyUpdate, JSON200: nil, } RotateWorkspaceAPITokenResponseOK = astrocore.RotateWorkspaceApiTokenResponse{ @@ -114,7 +115,7 @@ var ( HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: errorBodyUpdate, + Body: workspace.errorBodyUpdate, JSON200: nil, } DeleteWorkspaceAPITokenResponseOK = astrocore.DeleteWorkspaceApiTokenResponse{ @@ -126,7 +127,7 @@ var ( HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: errorBodyUpdate, + Body: workspace.errorBodyUpdate, } ) @@ -209,7 +210,7 @@ func TestCreateToken(t *testing.T) { err := CreateToken("", "Description 1", "WORKSPACE_MEMBER", "", 0, true, out, mockClient) - assert.Equal(t, ErrInvalidTokenName, err) + assert.Equal(t, workspace.ErrInvalidTokenName, err) }) } diff --git a/cmd/cloud/deployment.go b/cmd/cloud/deployment.go index 1aa0670ac..ab3700591 100644 --- a/cmd/cloud/deployment.go +++ b/cmd/cloud/deployment.go @@ -14,7 +14,6 @@ import ( "github.com/astronomer/astro-cli/cloud/organization" "github.com/astronomer/astro-cli/cloud/team" "github.com/astronomer/astro-cli/cloud/user" - "github.com/astronomer/astro-cli/cloud/workspace" "github.com/astronomer/astro-cli/pkg/httputil" "github.com/astronomer/astro-cli/pkg/input" "github.com/pkg/errors" @@ -1041,7 +1040,8 @@ func newOrgTokenManageCmd(out io.Writer) *cobra.Command { } cmd.SetOut(out) cmd.AddCommand( - newUpsertOrganizationTokenDeploymentRole(out), + newCreateOrganizationTokenDeploymentRole(out), + newUpdateOrganizationTokenDeploymentRole(out), newRemoveOrganizationTokenDeploymentRole(out), newListOrganizationTokensInDeployment(out), ) @@ -1057,20 +1057,21 @@ func newWorkspaceTokenManageCmd(out io.Writer) *cobra.Command { } cmd.SetOut(out) cmd.AddCommand( - newUpsertWorkspaceTokenDeploymentRole(out), + newCreateWorkspaceTokenDeploymentRole(out), + newUpdateWorkspaceTokenDeploymentRole(out), newRemoveWorkspaceTokenDeploymentRole(out), newListWorkspaceTokensInDeployment(out), ) return cmd } -func newUpsertOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { +func newCreateOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "upsert [ORG_TOKEN_ID]", - Short: "Upsert an Organization API token's Deployment Role", - Long: "Upsert an Organization API token's Deployment Role\n$astro deployment token organization-token upsert [ORG_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + Use: "create [ORG_TOKEN_ID]", + Short: "Create an Organization API token's Deployment Role", + Long: "Create an Organization API token's Deployment Role\n$astro deployment token organization-token create [ORG_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", RunE: func(cmd *cobra.Command, args []string) error { - return upsertOrgTokenToDeploymentRole(cmd, args, out) + return createOrgTokenToDeploymentRole(cmd, args, out) }, } cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") @@ -1079,13 +1080,28 @@ func newUpsertOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { return cmd } -func newUpsertWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { +func newUpdateOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "upsert [WORKSPACE_TOKEN_ID]", - Short: "Upsert a Workspace API token's Deployment Role", - Long: "Upsert a Workspace API token's Deployment Role\n$astro deployment token workspace-token upsert [WORKSPACE_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + Use: "update [ORG_TOKEN_ID]", + Short: "Update an Organization API token's Deployment Role", + Long: "Update an Organization API token's Deployment Role\n$astro deployment token organization-token update [ORG_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", RunE: func(cmd *cobra.Command, args []string) error { - return upsertWorkspaceTokenDeploymentRole(cmd, args, out) + return updateOrgTokenToDeploymentRole(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to update in a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Deployment role to grant to the "+ + "Organization API token. Possible values are DEPLOYMENT_ADMIN or a custom role name.") + return cmd +} + +func newCreateWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "create [WORKSPACE_TOKEN_ID]", + Short: "Create a Workspace API token's Deployment Role", + Long: "Create a Workspace API token's Deployment Role\n$astro deployment token workspace-token create [WORKSPACE_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + RunE: func(cmd *cobra.Command, args []string) error { + return createWorkspaceTokenDeploymentRole(cmd, args, out) }, } cmd.Flags().StringVarP(&orgTokenName, "workspace-token-name", "n", "", "The name of the WORKSPACE API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") @@ -1094,7 +1110,22 @@ func newUpsertWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { return cmd } -func upsertOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { +func newUpdateWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "update [WORKSPACE_TOKEN_ID]", + Short: "Update a Workspace API token's Deployment Role", + Long: "Update a Workspace API token's Deployment Role\n$astro deployment token workspace-token update [WORKSPACE_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + RunE: func(cmd *cobra.Command, args []string) error { + return updateWorkspaceTokenDeploymentRole(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "workspace-token-name", "n", "", "The name of the WORKSPACE API token you want to update in a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Deployment role to grant to the "+ + "Workspace API token. Possible values are DEPLOYMENT_ADMIN or a custom role name.") + return cmd +} + +func createOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } @@ -1109,10 +1140,47 @@ func upsertOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Wr } cmd.SilenceUsage = true - return organization.UpsertOrgTokenDeploymentRole(orgTokenID, orgTokenName, tokenRole, deploymentID, out, astroCoreClient, astroCoreIamClient) + return deployment.UpsertOrgTokenDeploymentRole(orgTokenID, orgTokenName, tokenRole, deploymentID, "create", out, astroCoreClient, astroCoreIamClient) +} + +func updateOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { + if deploymentID == "" { + return errors.New("flag --deployment-id is required") + } + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + orgTokenID = strings.ToLower(args[0]) + } + if tokenRole == "" { + // no role was provided so ask the user for it + tokenRole = input.Text("Enter a role for the new Deployment API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") + } + cmd.SilenceUsage = true + + return deployment.UpsertOrgTokenDeploymentRole(orgTokenID, orgTokenName, tokenRole, deploymentID, "update", out, astroCoreClient, astroCoreIamClient) +} + +func createWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { + if deploymentID == "" { + return errors.New("flag --deployment-id is required") + } + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + workspaceTokenID = strings.ToLower(args[0]) + } + + if tokenRole == "" { + // no role was provided so ask the user for it + tokenRole = input.Text("Enter a role for the new Deployment API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") + } + + cmd.SilenceUsage = true + return deployment.UpsertWorkspaceTokenDeploymentRole(workspaceTokenID, orgTokenName, tokenRole, workspaceID, deploymentID, "create", out, astroCoreClient, astroCoreIamClient) } -func upsertWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { +func updateWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } @@ -1128,7 +1196,7 @@ func upsertWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out i } cmd.SilenceUsage = true - return workspace.UpsertWorkspaceTokenDeploymentRole(workspaceTokenID, orgTokenName, tokenRole, workspaceID, deploymentID, out, astroCoreClient, astroCoreIamClient) + return deployment.UpsertWorkspaceTokenDeploymentRole(workspaceTokenID, orgTokenName, tokenRole, workspaceID, deploymentID, "update", out, astroCoreClient, astroCoreIamClient) } func newRemoveOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { diff --git a/cmd/cloud/workspace.go b/cmd/cloud/workspace.go index 6fa1c3faa..037ca971b 100644 --- a/cmd/cloud/workspace.go +++ b/cmd/cloud/workspace.go @@ -3,6 +3,7 @@ package cloud import ( "fmt" astrocore "github.com/astronomer/astro-cli/astro-client-core" + "github.com/astronomer/astro-cli/cloud/workspace-token" "io" "os" "strconv" @@ -384,20 +385,21 @@ func newWorkspaceOrgTokenManageCmd(out io.Writer) *cobra.Command { } cmd.SetOut(out) cmd.AddCommand( - newUpsertOrganizationTokenWorkspaceRole(out), + newCreateOrganizationTokenWorkspaceRole(out), + newUpdateOrganizationTokenWorkspaceRole(out), newRemoveOrganizationTokenWorkspaceRole(out), newListOrganizationTokensInWorkspace(out), ) return cmd } -func newUpsertOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { +func newCreateOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "upsert [ORG_TOKEN_ID]", - Short: "Upsert an Organization API token's Workspace Role", - Long: "Upsert an Organization API token's Workspace Role\n$astro workspace token organization-token upsert [ORG_TOKEN_ID] --name [token name] --role [" + allowedWorkspaceRoleNames + "].", + Use: "create [ORG_TOKEN_ID]", + Short: "Create an Organization API token's Workspace Role", + Long: "Create an Organization API token's Workspace Role\n$astro workspace token organization-token create [ORG_TOKEN_ID] --name [token name] --role [" + allowedWorkspaceRoleNames + "].", RunE: func(cmd *cobra.Command, args []string) error { - return upsertOrgTokenToWorkspaceRole(cmd, args, out) + return createOrgTokenWorkspaceRole(cmd, args, out) }, } cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to add to a Workspace. If the name contains a space, specify the entire name within quotes \"\" ") @@ -406,7 +408,37 @@ func newUpsertOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { return cmd } -func upsertOrgTokenToWorkspaceRole(cmd *cobra.Command, args []string, out io.Writer) error { +func newUpdateOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { + cmd := &cobra.Command{ + Use: "update [ORG_TOKEN_ID]", + Short: "Update an Organization API token's Workspace Role", + Long: "Update an Organization API token's Workspace Role\n$astro workspace token organization-token update [ORG_TOKEN_ID] --name [token name] --role [" + allowedWorkspaceRoleNames + "].", + RunE: func(cmd *cobra.Command, args []string) error { + return updateOrgTokenWorkspaceRole(cmd, args, out) + }, + } + cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to update in a Workspace. If the name contains a space, specify the entire name within quotes \"\" ") + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Workspace role to grant to the "+ + "Organization API token. Possible values are"+allowedWorkspaceRoleNamesProse) + return cmd +} + +func createOrgTokenWorkspaceRole(cmd *cobra.Command, args []string, out io.Writer) error { + // if an id was provided in the args we use it + if len(args) > 0 { + // make sure the id is lowercase + orgTokenID = strings.ToLower(args[0]) + } + if tokenRole == "" { + // no role was provided so ask the user for it + tokenRole = input.Text("Enter a role for the new Workspace API token. Possible values are " + allowedWorkspaceRoleNamesProse + ": ") + } + cmd.SilenceUsage = true + + return workspace_token.UpsertOrgTokenWorkspaceRole(orgTokenID, orgTokenName, tokenRole, workspaceID, "create", out, astroCoreClient, astroCoreIamClient) +} + +func updateOrgTokenWorkspaceRole(cmd *cobra.Command, args []string, out io.Writer) error { // if an id was provided in the args we use it if len(args) > 0 { // make sure the id is lowercase @@ -418,7 +450,7 @@ func upsertOrgTokenToWorkspaceRole(cmd *cobra.Command, args []string, out io.Wri } cmd.SilenceUsage = true - return organization.UpsertOrgTokenWorkspaceRole(orgTokenID, orgTokenName, tokenRole, workspaceID, out, astroCoreClient, astroCoreIamClient) + return workspace_token.UpsertOrgTokenWorkspaceRole(orgTokenID, orgTokenName, tokenRole, workspaceID, "update", out, astroCoreClient, astroCoreIamClient) } func newRemoveOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { @@ -442,7 +474,7 @@ func removeWorkspaceTokenFromDeploymentRole(cmd *cobra.Command, args []string, o } cmd.SilenceUsage = true - return workspace.RemoveOrgTokenWorkspaceRole(orgTokenID, orgTokenName, workspaceID, out, astroCoreClient, astroCoreIamClient) + return workspace_token.RemoveOrgTokenWorkspaceRole(orgTokenID, orgTokenName, workspaceID, out, astroCoreClient, astroCoreIamClient) } func newListOrganizationTokensInWorkspace(out io.Writer) *cobra.Command { @@ -462,7 +494,7 @@ func listOrganizationTokensInWorkspace(cmd *cobra.Command, args []string, out io tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{ "ORGANIZATION", } - return workspace.ListTokens(astroCoreClient, deploymentID, &tokenTypes, out) + return workspace_token.ListTokens(astroCoreClient, deploymentID, &tokenTypes, out) } func newWorkspaceTeamRemoveCmd(out io.Writer) *cobra.Command { @@ -651,7 +683,7 @@ func removeWorkspaceUser(cmd *cobra.Command, args []string, out io.Writer) error func listWorkspaceToken(cmd *cobra.Command, out io.Writer) error { cmd.SilenceUsage = true - return workspace.ListTokens(astroCoreClient, workspaceID, nil, out) + return workspace_token.ListTokens(astroCoreClient, workspaceID, nil, out) } func createWorkspaceToken(cmd *cobra.Command, out io.Writer) error { @@ -670,7 +702,7 @@ func createWorkspaceToken(cmd *cobra.Command, out io.Writer) error { } cmd.SilenceUsage = true - return workspace.CreateToken(tokenName, tokenDescription, tokenRole, workspaceID, tokenExpiration, cleanTokenOutput, out, astroCoreClient) + return workspace_token.CreateToken(tokenName, tokenDescription, tokenRole, workspaceID, tokenExpiration, cleanTokenOutput, out, astroCoreClient) } func updateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -681,7 +713,7 @@ func updateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro } cmd.SilenceUsage = true - return workspace.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, workspaceID, out, astroCoreClient, astroCoreIamClient) + return workspace_token.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, workspaceID, out, astroCoreClient, astroCoreIamClient) } func rotateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -691,7 +723,7 @@ func rotateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro tokenID = strings.ToLower(args[0]) } cmd.SilenceUsage = true - return workspace.RotateToken(tokenID, name, workspaceID, cleanTokenOutput, forceRotate, out, astroCoreClient, astroCoreIamClient) + return workspace_token.RotateToken(tokenID, name, workspaceID, cleanTokenOutput, forceRotate, out, astroCoreClient, astroCoreIamClient) } func deleteWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -702,7 +734,7 @@ func deleteWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro } cmd.SilenceUsage = true - return workspace.DeleteToken(tokenID, name, workspaceID, forceDelete, out, astroCoreClient, astroCoreIamClient) + return workspace_token.DeleteToken(tokenID, name, workspaceID, forceDelete, out, astroCoreClient, astroCoreIamClient) } func addOrgTokenToWorkspace(cmd *cobra.Command, args []string, out io.Writer) error { From 0de263ef4245e326149f69affa06b1bc7c5e0355 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 13:44:28 -0400 Subject: [PATCH 08/26] fix existing tests --- astro-client-core/mocks/client.go | 165 +++++++++++++ cloud/deployment/deployment_token_test.go | 167 ++++++++----- cloud/organization/organization_token.go | 4 + cloud/organization/organization_token_test.go | 227 +++++++++++++----- cloud/workspace-token/workspace_token.go | 2 +- cloud/workspace-token/workspace_token_test.go | 207 ++++++++++------ cmd/cloud/deployment_test.go | 8 +- cmd/cloud/organization_test.go | 25 +- cmd/cloud/workspace_test.go | 32 ++- 9 files changed, 641 insertions(+), 196 deletions(-) diff --git a/astro-client-core/mocks/client.go b/astro-client-core/mocks/client.go index c303d4c70..8f0301fe6 100644 --- a/astro-client-core/mocks/client.go +++ b/astro-client-core/mocks/client.go @@ -1766,6 +1766,39 @@ func (_m *ClientWithResponsesInterface) GetCustomRoleWithResponse(ctx context.Co return r0, r1 } +// GetDeployWithResponse provides a mock function with given fields: ctx, organizationId, deploymentId, deployId, params, reqEditors +func (_m *ClientWithResponsesInterface) GetDeployWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, params *astrocore.GetDeployParams, reqEditors ...astrocore.RequestEditorFn) (*astrocore.GetDeployResponse, error) { + _va := make([]interface{}, len(reqEditors)) + for _i := range reqEditors { + _va[_i] = reqEditors[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, organizationId, deploymentId, deployId, params) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *astrocore.GetDeployResponse + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, string, *astrocore.GetDeployParams, ...astrocore.RequestEditorFn) (*astrocore.GetDeployResponse, error)); ok { + return rf(ctx, organizationId, deploymentId, deployId, params, reqEditors...) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, string, *astrocore.GetDeployParams, ...astrocore.RequestEditorFn) *astrocore.GetDeployResponse); ok { + r0 = rf(ctx, organizationId, deploymentId, deployId, params, reqEditors...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*astrocore.GetDeployResponse) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, string, *astrocore.GetDeployParams, ...astrocore.RequestEditorFn) error); ok { + r1 = rf(ctx, organizationId, deploymentId, deployId, params, reqEditors...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetDeploymentApiTokenWithResponse provides a mock function with given fields: ctx, organizationId, deploymentId, apiTokenId, reqEditors func (_m *ClientWithResponsesInterface) GetDeploymentApiTokenWithResponse(ctx context.Context, organizationId string, deploymentId string, apiTokenId string, reqEditors ...astrocore.RequestEditorFn) (*astrocore.GetDeploymentApiTokenResponse, error) { _va := make([]interface{}, len(reqEditors)) @@ -2063,6 +2096,72 @@ func (_m *ClientWithResponsesInterface) GetOrganizationWithResponse(ctx context. return r0, r1 } +// GetSelfUserGitAppAuthorizationWithResponse provides a mock function with given fields: ctx, gitProvider, reqEditors +func (_m *ClientWithResponsesInterface) GetSelfUserGitAppAuthorizationWithResponse(ctx context.Context, gitProvider astrocore.GetSelfUserGitAppAuthorizationParamsGitProvider, reqEditors ...astrocore.RequestEditorFn) (*astrocore.GetSelfUserGitAppAuthorizationResponse, error) { + _va := make([]interface{}, len(reqEditors)) + for _i := range reqEditors { + _va[_i] = reqEditors[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, gitProvider) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *astrocore.GetSelfUserGitAppAuthorizationResponse + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, astrocore.GetSelfUserGitAppAuthorizationParamsGitProvider, ...astrocore.RequestEditorFn) (*astrocore.GetSelfUserGitAppAuthorizationResponse, error)); ok { + return rf(ctx, gitProvider, reqEditors...) + } + if rf, ok := ret.Get(0).(func(context.Context, astrocore.GetSelfUserGitAppAuthorizationParamsGitProvider, ...astrocore.RequestEditorFn) *astrocore.GetSelfUserGitAppAuthorizationResponse); ok { + r0 = rf(ctx, gitProvider, reqEditors...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*astrocore.GetSelfUserGitAppAuthorizationResponse) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, astrocore.GetSelfUserGitAppAuthorizationParamsGitProvider, ...astrocore.RequestEditorFn) error); ok { + r1 = rf(ctx, gitProvider, reqEditors...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetSelfUserGitAppInstallationWithResponse provides a mock function with given fields: ctx, gitProvider, reqEditors +func (_m *ClientWithResponsesInterface) GetSelfUserGitAppInstallationWithResponse(ctx context.Context, gitProvider astrocore.GetSelfUserGitAppInstallationParamsGitProvider, reqEditors ...astrocore.RequestEditorFn) (*astrocore.GetSelfUserGitAppInstallationResponse, error) { + _va := make([]interface{}, len(reqEditors)) + for _i := range reqEditors { + _va[_i] = reqEditors[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, gitProvider) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *astrocore.GetSelfUserGitAppInstallationResponse + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, astrocore.GetSelfUserGitAppInstallationParamsGitProvider, ...astrocore.RequestEditorFn) (*astrocore.GetSelfUserGitAppInstallationResponse, error)); ok { + return rf(ctx, gitProvider, reqEditors...) + } + if rf, ok := ret.Get(0).(func(context.Context, astrocore.GetSelfUserGitAppInstallationParamsGitProvider, ...astrocore.RequestEditorFn) *astrocore.GetSelfUserGitAppInstallationResponse); ok { + r0 = rf(ctx, gitProvider, reqEditors...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*astrocore.GetSelfUserGitAppInstallationResponse) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, astrocore.GetSelfUserGitAppInstallationParamsGitProvider, ...astrocore.RequestEditorFn) error); ok { + r1 = rf(ctx, gitProvider, reqEditors...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetSelfUserRepositoryBranchWithResponse provides a mock function with given fields: ctx, gitProvider, gitAccount, gitRepository, gitBranch, reqEditors func (_m *ClientWithResponsesInterface) GetSelfUserRepositoryBranchWithResponse(ctx context.Context, gitProvider astrocore.GetSelfUserRepositoryBranchParamsGitProvider, gitAccount string, gitRepository string, gitBranch string, reqEditors ...astrocore.RequestEditorFn) (*astrocore.GetSelfUserRepositoryBranchResponse, error) { _va := make([]interface{}, len(reqEditors)) @@ -2393,6 +2492,72 @@ func (_m *ClientWithResponsesInterface) ListClustersWithResponse(ctx context.Con return r0, r1 } +// ListDeployStepLogsWithResponse provides a mock function with given fields: ctx, organizationId, deploymentId, deployId, deployStepId, params, reqEditors +func (_m *ClientWithResponsesInterface) ListDeployStepLogsWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, deployStepId string, params *astrocore.ListDeployStepLogsParams, reqEditors ...astrocore.RequestEditorFn) (*astrocore.ListDeployStepLogsResponse, error) { + _va := make([]interface{}, len(reqEditors)) + for _i := range reqEditors { + _va[_i] = reqEditors[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, organizationId, deploymentId, deployId, deployStepId, params) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *astrocore.ListDeployStepLogsResponse + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, string, string, *astrocore.ListDeployStepLogsParams, ...astrocore.RequestEditorFn) (*astrocore.ListDeployStepLogsResponse, error)); ok { + return rf(ctx, organizationId, deploymentId, deployId, deployStepId, params, reqEditors...) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, string, string, *astrocore.ListDeployStepLogsParams, ...astrocore.RequestEditorFn) *astrocore.ListDeployStepLogsResponse); ok { + r0 = rf(ctx, organizationId, deploymentId, deployId, deployStepId, params, reqEditors...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*astrocore.ListDeployStepLogsResponse) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, string, string, *astrocore.ListDeployStepLogsParams, ...astrocore.RequestEditorFn) error); ok { + r1 = rf(ctx, organizationId, deploymentId, deployId, deployStepId, params, reqEditors...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ListDeployStepsWithResponse provides a mock function with given fields: ctx, organizationId, deploymentId, deployId, params, reqEditors +func (_m *ClientWithResponsesInterface) ListDeployStepsWithResponse(ctx context.Context, organizationId string, deploymentId string, deployId string, params *astrocore.ListDeployStepsParams, reqEditors ...astrocore.RequestEditorFn) (*astrocore.ListDeployStepsResponse, error) { + _va := make([]interface{}, len(reqEditors)) + for _i := range reqEditors { + _va[_i] = reqEditors[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, organizationId, deploymentId, deployId, params) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *astrocore.ListDeployStepsResponse + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, string, *astrocore.ListDeployStepsParams, ...astrocore.RequestEditorFn) (*astrocore.ListDeployStepsResponse, error)); ok { + return rf(ctx, organizationId, deploymentId, deployId, params, reqEditors...) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, string, *astrocore.ListDeployStepsParams, ...astrocore.RequestEditorFn) *astrocore.ListDeployStepsResponse); ok { + r0 = rf(ctx, organizationId, deploymentId, deployId, params, reqEditors...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*astrocore.ListDeployStepsResponse) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, string, *astrocore.ListDeployStepsParams, ...astrocore.RequestEditorFn) error); ok { + r1 = rf(ctx, organizationId, deploymentId, deployId, params, reqEditors...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // ListDeploymentApiTokensWithResponse provides a mock function with given fields: ctx, organizationId, deploymentId, params, reqEditors func (_m *ClientWithResponsesInterface) ListDeploymentApiTokensWithResponse(ctx context.Context, organizationId string, deploymentId string, params *astrocore.ListDeploymentApiTokensParams, reqEditors ...astrocore.RequestEditorFn) (*astrocore.ListDeploymentApiTokensResponse, error) { _va := make([]interface{}, len(reqEditors)) diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 03662c52b..35367b4bd 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -3,6 +3,8 @@ package deployment import ( "bytes" "encoding/json" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "net/http" "os" "testing" @@ -22,31 +24,34 @@ var ( fullName1 = "User 1" fullName2 = "User 2" token = "token" - apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: []astrocore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} - apiTokens = []astrocore.ApiToken{ - apiToken1, - {Id: "token2", Name: "Token 2", Description: description2, Type: "ORGANIZATION", Roles: []astrocore.ApiTokenRole{{EntityId: "otherDeployment", EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{ApiTokenName: &fullName2}}, - } - apiTokens2 = []astrocore.ApiToken{ - apiToken1, - {Id: "token2", Name: "Token 2", Description: description2, Type: "DEPLOYMENT", Roles: []astrocore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, - } - GetDeploymentAPITokenResponseOK = astrocore.GetDeploymentApiTokenResponse{ + + iamApiToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &apiToken1, + JSON200: &iamApiToken, } - getTokenErrorBodyList, _ = json.Marshal(astrocore.Error{ + errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", }) - GetDeploymentAPITokenResponseError = astrocore.GetDeploymentApiTokenResponse{ + GetAPITokensResponseError = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: getTokenErrorBodyList, + Body: errorTokenGet, JSON200: nil, } + + apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: []astrocore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} + apiTokens = []astrocore.ApiToken{ + apiToken1, + {Id: "token2", Name: "Token 2", Description: description2, Type: "ORGANIZATION", Roles: []astrocore.ApiTokenRole{{EntityId: "otherDeployment", EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{ApiTokenName: &fullName2}}, + } + apiTokens2 = []astrocore.ApiToken{ + apiToken1, + {Id: "token2", Name: "Token 2", Description: description2, Type: "DEPLOYMENT", Roles: []astrocore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, + } ListDeploymentAPITokensResponseOK = astrocore.ListDeploymentApiTokensResponse{ HTTPResponse: &http.Response{ StatusCode: 200, @@ -142,7 +147,7 @@ func TestListTokens(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Twice() - err := ListTokens(mockClient, "", out) + err := ListTokens(mockClient, "", nil, out) assert.NoError(t, err) }) @@ -152,7 +157,7 @@ func TestListTokens(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Twice() - err := ListTokens(mockClient, "otherDeployment", out) + err := ListTokens(mockClient, "otherDeployment", nil, out) assert.NoError(t, err) }) @@ -162,7 +167,7 @@ func TestListTokens(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseError, nil).Twice() - err := ListTokens(mockClient, "otherDeployment", out) + err := ListTokens(mockClient, "otherDeployment", nil, out) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -170,7 +175,7 @@ func TestListTokens(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := ListTokens(mockClient, "", out) + err := ListTokens(mockClient, "", nil, out) assert.Error(t, err) }) @@ -225,15 +230,20 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseOK, nil).Twice() mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "", "", "", "", out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path no id", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Twice() mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseOK, nil) @@ -248,13 +258,16 @@ func TestUpdateToken(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpdateToken("", "", "", "", "", "", out, mockClient) + err = UpdateToken("", "", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path multiple name", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponse2O0, nil).Twice() mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseOK, nil) @@ -269,72 +282,82 @@ func TestUpdateToken(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpdateToken("", "Token 1", "", "", "", "", out, mockClient) + err = UpdateToken("", "Token 1", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseOK, nil).Twice() mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "mockNewName", "mockDescription", "", "", out, mockClient) + err := UpdateToken("token1", "", "mockNewName", "mockDescription", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("error path when listDeploymentTokens returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseError, nil) - err := UpdateToken("", "", "", "", "", "", out, mockClient) + err := UpdateToken("", "", "", "", "", "", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) t.Run("error path when listDeploymentToken returns an not found error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) - err := UpdateToken("", "invalid name", "", "", "", "", out, mockClient) + err := UpdateToken("", "invalid name", "", "", "", "", out, mockClient, mockIamClient) assert.Equal(t, ErrDeploymentTokenNotFound, err) }) t.Run("error path when getDeploymentToken returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseError, nil) - err := UpdateToken("tokenId", "", "", "", "", "", out, mockClient) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + err := UpdateToken("tokenId", "", "", "", "", "", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) t.Run("error path when UpdateDeploymentApiTokenWithResponse returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseOK, nil) mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseError, nil) - err := UpdateToken("token3", "", "", "", "", "", out, mockClient) + err := UpdateToken("token3", "", "", "", "", "", out, mockClient, mockIamClient) assert.Equal(t, "failed to update token", err.Error()) }) t.Run("error path when there is no context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := UpdateToken("token1", "", "", "", "", "", out, mockClient) + err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) assert.Error(t, err) }) t.Run("Happy path when applying deployment role", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseOK, nil) - err := UpdateToken("", apiToken1.Name, "", "", "DEPLOYMENT_MEMBER", "", out, mockClient) + err := UpdateToken("", apiToken1.Name, "", "", "DEPLOYMENT_MEMBER", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) } @@ -343,85 +366,103 @@ func TestRotateToken(t *testing.T) { t.Run("happy path - id provided", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseOK, nil) mockClient.On("RotateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateDeploymentAPITokenResponseOK, nil) - err := RotateToken("token1", "", "", false, true, out, mockClient) + err := RotateToken("token1", "", "", false, true, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path name provided", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) mockClient.On("RotateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateDeploymentAPITokenResponseOK, nil) - err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient) + err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path with confirmation", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) mockClient.On("RotateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateDeploymentAPITokenResponseOK, nil) - err := RotateToken("", apiToken1.Name, "", false, false, out, mockClient) + err := RotateToken("", apiToken1.Name, "", false, false, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path with clean output", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) mockClient.On("RotateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateDeploymentAPITokenResponseOK, nil) - err := RotateToken("", apiToken1.Name, "", true, false, out, mockClient) + err := RotateToken("", apiToken1.Name, "", true, false, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("error path when there is no context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := RotateToken("token1", "", "", false, false, out, mockClient) + err := RotateToken("token1", "", "", false, false, out, mockClient, mockIamClient) assert.Error(t, err) }) t.Run("error path when listDeploymentTokens returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseError, nil) - err := RotateToken("", "", "", false, false, out, mockClient) + err := RotateToken("", "", "", false, false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) t.Run("error path when listDeploymentToken returns an not found error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) - err := RotateToken("", "invalid name", "", false, false, out, mockClient) + err := RotateToken("", "invalid name", "", false, false, out, mockClient, mockIamClient) assert.Equal(t, ErrDeploymentTokenNotFound, err) }) - t.Run("error path when getDeploymentToken returns an error", func(t *testing.T) { + t.Run("error path when getApiToken returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseError, nil) - err := RotateToken("token1", "", "", false, false, out, mockClient) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + err := RotateToken("token1", "", "", false, false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) t.Run("error path when RotateDeploymentApiTokenWithResponse returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) mockClient.On("RotateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateDeploymentAPITokenResponseError, nil) - err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient) + err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient, mockIamClient) assert.Equal(t, "failed to update token", err.Error()) }) } @@ -430,28 +471,35 @@ func TestDeleteToken(t *testing.T) { t.Run("happy path - delete deployment token - by name", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Twice() mockClient.On("DeleteDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteDeploymentAPITokenResponseOK, nil) - err := DeleteToken("", apiToken1.Name, "", true, out, mockClient) + err := DeleteToken("", apiToken1.Name, "", true, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path - delete deployment token - by id", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseOK, nil).Twice() mockClient.On("DeleteDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteDeploymentAPITokenResponseOK, nil) - err := DeleteToken("token1", "", "", true, out, mockClient) + err := DeleteToken("token1", "", "", true, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path - delete deployment token - no force", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseOK, nil).Twice() mockClient.On("DeleteDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteDeploymentAPITokenResponseOK, nil) // mock os.Stdin expectedInput := []byte("y") @@ -464,52 +512,59 @@ func TestDeleteToken(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = DeleteToken("token1", "", "", false, out, mockClient) + err = DeleteToken("token1", "", "", false, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("error path when there is no context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := DeleteToken("token1", "", "", true, out, mockClient) + err := DeleteToken("token1", "", "", true, out, mockClient, mockIamClient) assert.Error(t, err) }) - t.Run("error path when getDeploymentToken returns an error", func(t *testing.T) { + t.Run("error path when getApiToken returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetDeploymentAPITokenResponseError, nil) - err := DeleteToken("token1", "", "", true, out, mockClient) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + err := DeleteToken("token1", "", "", true, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) t.Run("error path when listDeploymentTokens returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseError, nil) - err := DeleteToken("", apiToken1.Name, "", true, out, mockClient) + err := DeleteToken("", apiToken1.Name, "", true, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) t.Run("error path when listDeploymentToken returns a not found error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) - err := DeleteToken("", "invalid name", "", true, out, mockClient) + err := DeleteToken("", "invalid name", "", true, out, mockClient, mockIamClient) assert.Equal(t, ErrDeploymentTokenNotFound, err) }) t.Run("error path when DeleteDeploymentApiTokenWithResponse returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) mockClient.On("DeleteDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteDeploymentAPITokenResponseError, nil) - err := DeleteToken("", apiToken1.Name, "", true, out, mockClient) + err := DeleteToken("", apiToken1.Name, "", true, out, mockClient, mockIamClient) assert.Equal(t, "failed to update token", err.Error()) }) } diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index 2abf57441..e431ea3df 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -78,6 +78,7 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli } apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} roles := *token.Roles + for i := range roles { if roles[i].EntityId == workspace { if roles[i].Role == role { @@ -302,6 +303,9 @@ func GetTokenFromInputOrUser(id, name, organization string, client astrocore.Cor // List all roles for a given organization Token func ListTokenRoles(id string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient, out io.Writer) (err error) { ctx, err := context.GetCurrentContext() + if err != nil { + return err + } apiToken, err := GetTokenFromInputOrUser(id, "", ctx.Organization, client, iamClient) if err != nil { return err diff --git a/cloud/organization/organization_token_test.go b/cloud/organization/organization_token_test.go index 39ed7b7c3..6fb0b590a 100644 --- a/cloud/organization/organization_token_test.go +++ b/cloud/organization/organization_token_test.go @@ -3,6 +3,8 @@ package organization import ( "bytes" "encoding/json" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "net/http" "os" "testing" @@ -17,12 +19,29 @@ import ( ) var ( - description1 = "Description 1" - description2 = "Description 2" - fullName1 = "User 1" - fullName2 = "User 2" - token = "token" - workspaceID = "ck05r3bor07h40d02y2hw4n4v" + description1 = "Description 1" + description2 = "Description 2" + fullName1 = "User 1" + fullName2 = "User 2" + token = "token" + workspaceID = "ck05r3bor07h40d02y2hw4n4v" + iamApiToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSAPCE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &iamApiToken, + } + errorTokenGet, _ = json.Marshal(astroiamcore.Error{ + Message: "failed to get token", + }) + GetAPITokensResponseError = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 500, + }, + Body: errorTokenGet, + JSON200: nil, + } apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "ORGANIZATION_MEMBER"}, {EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} apiToken2 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} @@ -154,45 +173,54 @@ func TestAddOrgTokenToWorkspace(t *testing.T) { t.Run("return error for invalid workspace role", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) - err := AddOrgTokenToWorkspace(selectedTokenID, selectedTokenName, "INVALID_ROLE", workspace, nil, nil) + err := AddOrgTokenToWorkspace(selectedTokenID, selectedTokenName, "INVALID_ROLE", workspace, nil, nil, nil) assert.Error(t, err) assert.Equal(t, user.ErrInvalidWorkspaceRole, err) }) t.Run("return error for failed to get current context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := AddOrgTokenToWorkspace(selectedTokenID, selectedTokenName, role, workspace, nil, mockClient) + err := AddOrgTokenToWorkspace(selectedTokenID, selectedTokenName, role, workspace, nil, mockClient, mockIamClient) assert.Error(t, err) }) t.Run("return error for failed to list organization tokens", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil) - err := AddOrgTokenToWorkspace("", selectedTokenName, role, workspace, nil, mockClient) + err := AddOrgTokenToWorkspace("", selectedTokenName, role, workspace, nil, mockClient, mockIamClient) assert.Error(t, err) assert.ErrorContains(t, err, "failed to list tokens") }) t.Run("return error for failed to select organization token", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) - err := AddOrgTokenToWorkspace("", "Invalid name", role, workspace, nil, mockClient) + err := AddOrgTokenToWorkspace("", "Invalid name", role, workspace, nil, mockClient, mockIamClient) assert.Error(t, err) assert.Equal(t, errOrganizationTokenNotFound, err) }) t.Run("return error for organization token already in workspace", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) - err := AddOrgTokenToWorkspace("", selectedTokenName, role, workspace, nil, mockClient) + err := AddOrgTokenToWorkspace("", selectedTokenName, "WORKSPACE_AUTHOR", workspace, nil, mockClient, mockIamClient) assert.Error(t, err) assert.Equal(t, errOrgTokenInWorkspace, err) }) @@ -200,20 +228,25 @@ func TestAddOrgTokenToWorkspace(t *testing.T) { t.Run("successfully add organization token to workspace using id", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) - err := AddOrgTokenToWorkspace(selectedTokenID, "", role, workspace, out, mockClient) + err := AddOrgTokenToWorkspace(selectedTokenID, "", role, workspace, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("return error for failed to get organization token", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseError, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) - err := AddOrgTokenToWorkspace(selectedTokenID, "", role, workspace, nil, mockClient) + err := AddOrgTokenToWorkspace(selectedTokenID, "", role, workspace, nil, mockClient, mockIamClient) assert.Error(t, err) assert.ErrorContains(t, err, "failed to get token") }) @@ -221,17 +254,23 @@ func TestAddOrgTokenToWorkspace(t *testing.T) { t.Run("successfully add organization token to workspace", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) - err := AddOrgTokenToWorkspace("", selectedTokenName2, role, workspace, out, mockClient) + err := AddOrgTokenToWorkspace("", selectedTokenName2, role, workspace, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("successfully select and add organization token to workspace", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) @@ -246,13 +285,16 @@ func TestAddOrgTokenToWorkspace(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = AddOrgTokenToWorkspace("", "", role, workspace, out, mockClient) + err = AddOrgTokenToWorkspace("", "", role, workspace, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("successfully select and add organization token to workspace 2", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponse2O0, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) @@ -267,7 +309,7 @@ func TestAddOrgTokenToWorkspace(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = AddOrgTokenToWorkspace("", selectedTokenName, role, workspace, out, mockClient) + err = AddOrgTokenToWorkspace("", selectedTokenName, role, workspace, out, mockClient, mockIamClient) assert.NoError(t, err) }) } @@ -348,16 +390,22 @@ func TestUpdateToken(t *testing.T) { t.Run("happy path", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil).Twice() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "", "", "", out, mockClient) + err := UpdateToken("token1", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path no id", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Twice() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) @@ -372,13 +420,16 @@ func TestUpdateToken(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpdateToken("", "", "", "", "", out, mockClient) + err = UpdateToken("", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path multiple name", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponse2O0, nil).Twice() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) @@ -393,91 +444,111 @@ func TestUpdateToken(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpdateToken("", "Token 1", "", "", "", out, mockClient) + err = UpdateToken("", "Token 1", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil).Twice() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "", "", "", out, mockClient) + err := UpdateToken("token1", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("error path when listOrganizationTokens returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil) - err := UpdateToken("", "", "", "", "", out, mockClient) + err := UpdateToken("", "", "", "", "", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) t.Run("error path when listOrganizationToken returns an not found error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) - err := UpdateToken("", "invalid name", "", "", "", out, mockClient) + err := UpdateToken("", "invalid name", "", "", "", out, mockClient, mockIamClient) assert.Equal(t, errOrganizationTokenNotFound, err) }) - t.Run("error path when getOrganizationToken returns an error", func(t *testing.T) { + t.Run("error path when getApiToken returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseError, nil) - err := UpdateToken("tokenId", "", "", "", "", out, mockClient) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + + err := UpdateToken("tokenId", "", "", "", "", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) t.Run("error path when UpdateOrganizationApiTokenWithResponse returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil) - err := UpdateToken("token3", "", "", "", "", out, mockClient) + err := UpdateToken("token3", "", "", "", "", out, mockClient, mockIamClient) assert.Equal(t, "failed to update token", err.Error()) }) t.Run("error path when there is no context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := UpdateToken("token1", "", "", "", "", out, mockClient) + err := UpdateToken("token1", "", "", "", "", out, mockClient, mockIamClient) assert.Error(t, err) }) t.Run("error path when workspace role is invalid returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "", "", "Invalid Role", out, mockClient) + err := UpdateToken("token1", "", "", "", "Invalid Role", out, mockClient, mockIamClient) assert.Equal(t, user.ErrInvalidOrganizationRole.Error(), err.Error()) }) t.Run("Happy path when applying workspace role", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) - err := UpdateToken("", apiToken1.Name, "", "", "ORGANIZATION_MEMBER", out, mockClient) + err := UpdateToken("", apiToken1.Name, "", "", "ORGANIZATION_MEMBER", out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("Happy path when applying organization role using id", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "", "", "ORGANIZATION_MEMBER", out, mockClient) + err := UpdateToken("token1", "", "", "", "ORGANIZATION_MEMBER", out, mockClient, mockIamClient) assert.NoError(t, err) }) } @@ -486,75 +557,91 @@ func TestRotateToken(t *testing.T) { t.Run("happy path - id provided", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("RotateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateOrganizationAPITokenResponseOK, nil) - err := RotateToken("token1", "", false, true, out, mockClient) + err := RotateToken("token1", "", false, true, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path name provided", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("RotateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateOrganizationAPITokenResponseOK, nil) - err := RotateToken("", apiToken1.Name, false, true, out, mockClient) + err := RotateToken("", apiToken1.Name, false, true, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path with confirmation", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("RotateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateOrganizationAPITokenResponseOK, nil) - err := RotateToken("", apiToken1.Name, true, false, out, mockClient) + err := RotateToken("", apiToken1.Name, true, false, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("error path when there is no context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := RotateToken("token1", "", false, false, out, mockClient) + err := RotateToken("token1", "", false, false, out, mockClient, mockIamClient) assert.Error(t, err) }) t.Run("error path when listOrganizationTokens returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil) - err := RotateToken("", "", false, false, out, mockClient) + err := RotateToken("", "", false, false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) t.Run("error path when listOrganizationToken returns an not found error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) - err := RotateToken("", "invalid name", false, false, out, mockClient) + err := RotateToken("", "invalid name", false, false, out, mockClient, mockIamClient) assert.Equal(t, errOrganizationTokenNotFound, err) }) - t.Run("error path when getOrganizationToken returns an error", func(t *testing.T) { + t.Run("error path when getApiToken returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseError, nil) - err := RotateToken("token1", "", false, false, out, mockClient) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + err := RotateToken("token1", "", false, false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) t.Run("error path when RotateOrganizationApiTokenWithResponse returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("RotateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateOrganizationAPITokenResponseError, nil) - err := RotateToken("", apiToken1.Name, false, true, out, mockClient) + err := RotateToken("", apiToken1.Name, false, true, out, mockClient, mockIamClient) assert.Equal(t, "failed to update token", err.Error()) }) } @@ -563,75 +650,91 @@ func TestDeleteToken(t *testing.T) { t.Run("happy path - delete workspace token - by name", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Twice() mockClient.On("DeleteOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteOrganizationAPITokenResponseOK, nil) - err := DeleteToken("", apiToken1.Name, false, out, mockClient) + err := DeleteToken("", apiToken1.Name, false, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path - delete workspace token - by id", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil).Twice() mockClient.On("DeleteOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteOrganizationAPITokenResponseOK, nil) - err := DeleteToken("token1", "", false, out, mockClient) + err := DeleteToken("token1", "", false, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("happy path - remove organization token", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Twice() mockClient.On("DeleteOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteOrganizationAPITokenResponseOK, nil) - err := DeleteToken("", apiToken1.Name, false, out, mockClient) + err := DeleteToken("", apiToken1.Name, false, out, mockClient, mockIamClient) assert.NoError(t, err) }) t.Run("error path when there is no context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := DeleteToken("token1", "", false, out, mockClient) + err := DeleteToken("token1", "", false, out, mockClient, mockIamClient) assert.Error(t, err) }) - t.Run("error path when getOrganizationToken returns an error", func(t *testing.T) { + t.Run("error path when getApiToken returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseError, nil) - err := DeleteToken("token1", "", false, out, mockClient) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + err := DeleteToken("token1", "", false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) t.Run("error path when listOrganizationTokens returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil) - err := DeleteToken("", apiToken1.Name, false, out, mockClient) + err := DeleteToken("", apiToken1.Name, false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) t.Run("error path when listOrganizationToken returns a not found error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) - err := DeleteToken("", "invalid name", false, out, mockClient) + err := DeleteToken("", "invalid name", false, out, mockClient, mockIamClient) assert.Equal(t, errOrganizationTokenNotFound, err) }) t.Run("error path when DeleteOrganizationApiTokenWithResponse returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("DeleteOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteOrganizationAPITokenResponseError, nil) - err := DeleteToken("", apiToken1.Name, true, out, mockClient) + err := DeleteToken("", apiToken1.Name, true, out, mockClient, mockIamClient) assert.Equal(t, "failed to update token", err.Error()) }) } @@ -640,32 +743,39 @@ func TestListTokenRoles(t *testing.T) { t.Run("happy path - list token roles by id", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil).Twice() - err := ListTokenRoles("token1", mockClient, out) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + err := ListTokenRoles("token1", mockClient, mockIamClient, out) assert.NoError(t, err) }) t.Run("error path - list token roles by id - api error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseError, nil) - err := ListTokenRoles("token1", mockClient, out) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + err := ListTokenRoles("token1", mockClient, mockIamClient, out) assert.ErrorContains(t, err, "failed to get token") }) t.Run("error path - list token roles by id - no context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := ListTokenRoles("token1", mockClient, out) + err := ListTokenRoles("token1", mockClient, mockIamClient, out) assert.Error(t, err) }) t.Run("happy path - list token roles no id", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Twice() expectedInput := []byte("1") @@ -678,13 +788,14 @@ func TestListTokenRoles(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = ListTokenRoles("", mockClient, out) + err = ListTokenRoles("", mockClient, mockIamClient, out) assert.NoError(t, err) }) t.Run("error path - list token roles no id - list tokens api error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil).Twice() expectedInput := []byte("1") @@ -697,7 +808,7 @@ func TestListTokenRoles(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = ListTokenRoles("", mockClient, out) + err = ListTokenRoles("", mockClient, mockIamClient, out) assert.ErrorContains(t, err, "failed to list tokens") }) } diff --git a/cloud/workspace-token/workspace_token.go b/cloud/workspace-token/workspace_token.go index 41dc1134e..ac70cee45 100644 --- a/cloud/workspace-token/workspace_token.go +++ b/cloud/workspace-token/workspace_token.go @@ -553,7 +553,7 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie if err != nil { return err } - fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) + fmt.Fprintf(out, "Astro Organization API token %s was successfully removed from the Deployment\n", token.Name) return nil } diff --git a/cloud/workspace-token/workspace_token_test.go b/cloud/workspace-token/workspace_token_test.go index a47e31e9a..33a0da1bd 100644 --- a/cloud/workspace-token/workspace_token_test.go +++ b/cloud/workspace-token/workspace_token_test.go @@ -3,6 +3,8 @@ package workspace_token import ( "bytes" "encoding/json" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "github.com/astronomer/astro-cli/cloud/workspace" "net/http" "os" @@ -18,37 +20,38 @@ import ( ) var ( - workspaceID = "ck05r3bor07h40d02y2hw4n4v" - description1 = "Description 1" - description2 = "Description 2" - fullName1 = "User 1" - fullName2 = "User 2" - token = "token" - apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} - apiTokens = []astrocore.ApiToken{ - apiToken1, - {Id: "token2", Name: "Token 2", Description: description2, Type: "ORGANIZATION", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, - } - apiTokens2 = []astrocore.ApiToken{ - apiToken1, - {Id: "token2", Name: "Token 2", Description: description2, Type: "WORKSPACE", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, - } - GetWorkspaceAPITokenResponseOK = astrocore.GetWorkspaceApiTokenResponse{ + workspaceID = "ck05r3bor07h40d02y2hw4n4v" + description1 = "Description 1" + description2 = "Description 2" + fullName1 = "User 1" + fullName2 = "User 2" + token = "token" + iamApiToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &apiToken1, + JSON200: &iamApiToken, } - getTokenErrorBodyList, _ = json.Marshal(astrocore.Error{ + errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", }) - GetWorkspaceAPITokenResponseError = astrocore.GetWorkspaceApiTokenResponse{ + GetAPITokensResponseError = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: getTokenErrorBodyList, + Body: errorTokenGet, JSON200: nil, } + apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} + apiTokens = []astrocore.ApiToken{ + apiToken1, + {Id: "token2", Name: "Token 2", Description: description2, Type: "ORGANIZATION", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, + } + apiTokens2 = []astrocore.ApiToken{ + apiToken1, + {Id: "token2", Name: "Token 2", Description: description2, Type: "WORKSPACE", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, + } ListWorkspaceAPITokensResponseOK = astrocore.ListWorkspaceApiTokensResponse{ HTTPResponse: &http.Response{ StatusCode: 200, @@ -85,11 +88,16 @@ var ( }, JSON200: &apiToken1, } + + errorBodyCreate, _ = json.Marshal(astrocore.Error{ + Message: "failed to create workspace token", + }) + CreateWorkspaceAPITokenResponseError = astrocore.CreateWorkspaceApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: workspace.errorBodyCreate, + Body: errorBodyCreate, JSON200: nil, } UpdateWorkspaceAPITokenResponseOK = astrocore.UpdateWorkspaceApiTokenResponse{ @@ -98,11 +106,16 @@ var ( }, JSON200: &apiToken1, } + + errorBodyUpdate, _ = json.Marshal(astrocore.Error{ + Message: "failed to update workspace token", + }) + UpdateWorkspaceAPITokenResponseError = astrocore.UpdateWorkspaceApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: workspace.errorBodyUpdate, + Body: errorBodyUpdate, JSON200: nil, } RotateWorkspaceAPITokenResponseOK = astrocore.RotateWorkspaceApiTokenResponse{ @@ -115,7 +128,7 @@ var ( HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: workspace.errorBodyUpdate, + Body: errorBodyUpdate, JSON200: nil, } DeleteWorkspaceAPITokenResponseOK = astrocore.DeleteWorkspaceApiTokenResponse{ @@ -127,7 +140,7 @@ var ( HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: workspace.errorBodyUpdate, + Body: errorBodyUpdate, } ) @@ -137,7 +150,7 @@ func TestListTokens(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Twice() - err := ListTokens(mockClient, "", out) + err := ListTokens(mockClient, "", nil, out) assert.NoError(t, err) }) @@ -147,7 +160,7 @@ func TestListTokens(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Twice() - err := ListTokens(mockClient, "otherWorkspace", out) + err := ListTokens(mockClient, "otherWorkspace", nil, out) assert.NoError(t, err) }) @@ -157,7 +170,7 @@ func TestListTokens(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseError, nil).Twice() - err := ListTokens(mockClient, "otherWorkspace", out) + err := ListTokens(mockClient, "otherWorkspace", nil, out) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -165,7 +178,7 @@ func TestListTokens(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := ListTokens(mockClient, "", out) + err := ListTokens(mockClient, "", nil, out) assert.Error(t, err) }) @@ -219,9 +232,11 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseOK, nil).Twice() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "", "", "", "", out, mockClient) + + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -231,6 +246,9 @@ func TestUpdateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Twice() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) + + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -242,7 +260,7 @@ func TestUpdateToken(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpdateToken("", "", "", "", "", "", out, mockClient) + err = UpdateToken("", "", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -252,6 +270,9 @@ func TestUpdateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponse2O0, nil).Twice() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) + + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -263,7 +284,7 @@ func TestUpdateToken(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpdateToken("", "Token 1", "", "", "", "", out, mockClient) + err = UpdateToken("", "Token 1", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -271,9 +292,11 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseOK, nil).Twice() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "", "", "", "", out, mockClient) + + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -282,7 +305,8 @@ func TestUpdateToken(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseError, nil) - err := UpdateToken("", "", "", "", "", "", out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := UpdateToken("", "", "", "", "", "", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -290,17 +314,19 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) - err := UpdateToken("", "invalid name", "", "", "", "", out, mockClient) - assert.Equal(t, ErrWorkspaceTokenNotFound, err) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseError, nil) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := UpdateToken("", "invalid name", "", "", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") }) - t.Run("error path when getWorkspaceToken returns an error", func(t *testing.T) { + t.Run("error path when getApiToken returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseError, nil) - err := UpdateToken("tokenId", "", "", "", "", "", out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + err := UpdateToken("tokenId", "", "", "", "", "", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) @@ -308,17 +334,20 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseOK, nil) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseError, nil) - err := UpdateToken("token3", "", "", "", "", "", out, mockClient) - assert.Equal(t, "failed to update workspace", err.Error()) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := UpdateToken("token3", "", "", "", "", "", out, mockClient, mockIamClient) + assert.Equal(t, "failed to update workspace token", err.Error()) }) t.Run("error path when there is no context", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := UpdateToken("token1", "", "", "", "", "", out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) assert.Error(t, err) }) @@ -326,9 +355,11 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseOK, nil) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) - err := UpdateToken("token1", "", "", "", "Invalid Role", "", out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := UpdateToken("token1", "", "", "", "Invalid Role", "", out, mockClient, mockIamClient) assert.Equal(t, user.ErrInvalidWorkspaceRole.Error(), err.Error()) }) t.Run("Happy path when applying workspace role", func(t *testing.T) { @@ -337,7 +368,10 @@ func TestUpdateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) - err := UpdateToken("", apiToken1.Name, "", "", "WORKSPACE_MEMBER", "", out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := UpdateToken("", apiToken1.Name, "", "", "WORKSPACE_MEMBER", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) } @@ -347,9 +381,11 @@ func TestRotateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseOK, nil) mockClient.On("RotateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateWorkspaceAPITokenResponseOK, nil) - err := RotateToken("token1", "", "", false, true, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := RotateToken("token1", "", "", false, true, out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -359,7 +395,10 @@ func TestRotateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("RotateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateWorkspaceAPITokenResponseOK, nil) - err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -369,7 +408,10 @@ func TestRotateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("RotateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateWorkspaceAPITokenResponseOK, nil) - err := RotateToken("", apiToken1.Name, "", true, false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := RotateToken("", apiToken1.Name, "", true, false, out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -377,7 +419,8 @@ func TestRotateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := RotateToken("token1", "", "", false, false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := RotateToken("token1", "", "", false, false, out, mockClient, mockIamClient) assert.Error(t, err) }) @@ -386,7 +429,8 @@ func TestRotateToken(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseError, nil) - err := RotateToken("", "", "", false, false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := RotateToken("", "", "", false, false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -395,7 +439,8 @@ func TestRotateToken(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) - err := RotateToken("", "invalid name", "", false, false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := RotateToken("", "invalid name", "", false, false, out, mockClient, mockIamClient) assert.Equal(t, ErrWorkspaceTokenNotFound, err) }) @@ -403,8 +448,9 @@ func TestRotateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseError, nil) - err := RotateToken("token1", "", "", false, false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + err := RotateToken("token1", "", "", false, false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) @@ -414,8 +460,11 @@ func TestRotateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("RotateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateWorkspaceAPITokenResponseError, nil) - err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient) - assert.Equal(t, "failed to update workspace", err.Error()) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient, mockIamClient) + assert.Equal(t, "failed to update workspace token", err.Error()) }) } @@ -426,7 +475,10 @@ func TestDeleteToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Twice() mockClient.On("DeleteWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteWorkspaceAPITokenResponseOK, nil) - err := DeleteToken("", apiToken1.Name, "", false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := DeleteToken("", apiToken1.Name, "", false, out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -434,9 +486,11 @@ func TestDeleteToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseOK, nil).Twice() mockClient.On("DeleteWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteWorkspaceAPITokenResponseOK, nil) - err := DeleteToken("token1", "", "", false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := DeleteToken("token1", "", "", false, out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -446,7 +500,10 @@ func TestDeleteToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Twice() mockClient.On("DeleteWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteWorkspaceAPITokenResponseOK, nil) - err := DeleteToken("", apiToken1.Name, "", false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := DeleteToken("", apiToken1.Name, "", false, out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -454,16 +511,19 @@ func TestDeleteToken(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - err := DeleteToken("token1", "", "", false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := DeleteToken("token1", "", "", false, out, mockClient, mockIamClient) assert.Error(t, err) }) - t.Run("error path when getWorkspaceToken returns an error", func(t *testing.T) { + t.Run("error path when getApiToken returns an error", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetWorkspaceAPITokenResponseError, nil) - err := DeleteToken("token1", "", "", false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + + err := DeleteToken("token1", "", "", false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) @@ -472,7 +532,8 @@ func TestDeleteToken(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseError, nil) - err := DeleteToken("", apiToken1.Name, "", false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := DeleteToken("", apiToken1.Name, "", false, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -481,7 +542,8 @@ func TestDeleteToken(t *testing.T) { out := new(bytes.Buffer) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) - err := DeleteToken("", "invalid name", "", false, out, mockClient) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + err := DeleteToken("", "invalid name", "", false, out, mockClient, mockIamClient) assert.Equal(t, ErrWorkspaceTokenNotFound, err) }) @@ -491,8 +553,11 @@ func TestDeleteToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("DeleteWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteWorkspaceAPITokenResponseError, nil) - err := DeleteToken("", apiToken1.Name, "", true, out, mockClient) - assert.Equal(t, "failed to update workspace", err.Error()) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + + err := DeleteToken("", apiToken1.Name, "", true, out, mockClient, mockIamClient) + assert.Equal(t, "failed to update workspace token", err.Error()) }) } diff --git a/cmd/cloud/deployment_test.go b/cmd/cloud/deployment_test.go index 29a8908e9..c454b3e24 100644 --- a/cmd/cloud/deployment_test.go +++ b/cmd/cloud/deployment_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "io" "net/http" "os" @@ -2124,7 +2125,7 @@ func TestDeploymentTokenCreate(t *testing.T) { } func TestDeploymentTokenUpdate(t *testing.T) { - expectedHelp := "Update a Deployment or Organaization API token" + expectedHelp := "Update a Deployment API token" testUtil.InitTestConfig(testUtil.LocalPlatform) tokenID = "" @@ -2149,6 +2150,11 @@ func TestDeploymentTokenUpdate(t *testing.T) { mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&MutateDeploymentAPITokenRoleResponseError, nil) astroCoreClient = mockClient + + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "update", "--name", tokenName1, "--deployment-id", mockDeploymentID} _, err := execDeploymentCmd(cmdArgs...) assert.ErrorContains(t, err, "failed to update api token") diff --git a/cmd/cloud/organization_test.go b/cmd/cloud/organization_test.go index 66f2c4697..2d710415a 100644 --- a/cmd/cloud/organization_test.go +++ b/cmd/cloud/organization_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "io" "net/http" "os" @@ -1247,6 +1248,11 @@ func TestOrganizationTokenUpdate(t *testing.T) { mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil) astroCoreClient = mockClient + + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "update", "--name", tokenName1} _, err := execOrganizationCmd(cmdArgs...) assert.ErrorContains(t, err, "failed to update token") @@ -1483,13 +1489,15 @@ func TestOrganizationTokenListRoles(t *testing.T) { }) t.Run("any errors from api are returned and token roles are not listed", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) - mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseError, nil).Once() - astroCoreClient = mockClient + + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil) + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "roles", mockTokenID} _, err := execOrganizationCmd(cmdArgs...) assert.ErrorContains(t, err, "failed to get token") - mockClient.AssertExpectations(t) + mockIamClient.AssertExpectations(t) }) t.Run("any context errors from api are returned and token roles are not listed", func(t *testing.T) { testUtil.InitTestConfig(testUtil.Initial) @@ -1503,13 +1511,14 @@ func TestOrganizationTokenListRoles(t *testing.T) { t.Run("token roles are listed", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) - mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil).Once() - astroCoreClient = mockClient + + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "roles", mockTokenID} _, err := execOrganizationCmd(cmdArgs...) assert.NoError(t, err) - mockClient.AssertExpectations(t) + mockIamClient.AssertExpectations(t) }) } diff --git a/cmd/cloud/workspace_test.go b/cmd/cloud/workspace_test.go index db220c633..ab7cd2235 100644 --- a/cmd/cloud/workspace_test.go +++ b/cmd/cloud/workspace_test.go @@ -11,6 +11,8 @@ import ( astrocore "github.com/astronomer/astro-cli/astro-client-core" astrocore_mocks "github.com/astronomer/astro-cli/astro-client-core/mocks" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "github.com/astronomer/astro-cli/cloud/user" "github.com/astronomer/astro-cli/cloud/workspace" testUtil "github.com/astronomer/astro-cli/pkg/testing" @@ -1029,6 +1031,23 @@ var ( apiToken1, {Id: "token2", Name: "Token 2", Description: description2, Type: "Type 2", Roles: []astrocore.ApiTokenRole{{EntityId: mockWorkspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, } + iamApiToken = astroiamcore.ApiToken{Id: "token1", Name: tokenName1, Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: mockWorkspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &iamApiToken, + } + errorTokenGet, _ = json.Marshal(astroiamcore.Error{ + Message: "failed to get token", + }) + GetAPITokensResponseError = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 500, + }, + Body: errorTokenGet, + JSON200: nil, + } ListWorkspaceAPITokensResponseOK = astrocore.ListWorkspaceApiTokensResponse{ HTTPResponse: &http.Response{ StatusCode: 200, @@ -1253,9 +1272,12 @@ func TestWorkspaceTokenUpdate(t *testing.T) { t.Run("any errors from api are returned and token is not updated", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseError, nil) astroCoreClient = mockClient + astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "update", "--name", tokenName1} _, err := execWorkspaceCmd(cmdArgs...) assert.ErrorContains(t, err, "failed to update token") @@ -1551,6 +1573,10 @@ func TestWorkspaceTokenAdd(t *testing.T) { mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) astroCoreClient = mockClient + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "add", "--org-token-name", tokenName2, "--role", "WORKSPACE_MEMBER"} _, err := execWorkspaceCmd(cmdArgs...) assert.NoError(t, err) @@ -1576,11 +1602,15 @@ func TestWorkspaceTokenAdd(t *testing.T) { _, err = execWorkspaceCmd(cmdArgs...) assert.NoError(t, err) }) - t.Run("token is created with no role provided", func(t *testing.T) { + t.Run("token is added with no role provided", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + astroCoreIamClient = mockIamClient + // mock os.Stdin expectedInput := []byte("1") r, w, err := os.Pipe() From b0f7cc8b57feaff20fea4e342a82f32f24bc52b1 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 14:21:45 -0400 Subject: [PATCH 09/26] lint --- astro-client-iam-core/client.go | 4 +- cloud/deployment/deployment_token.go | 51 ++++++++------- cloud/deployment/deployment_token_test.go | 8 +-- cloud/organization/organization_token.go | 3 +- cloud/organization/organization_token_test.go | 8 +-- cloud/workspace-token/workspace_token.go | 62 ++++++------------- cloud/workspace-token/workspace_token_test.go | 12 ++-- cmd/cloud/deployment.go | 12 ++-- cmd/cloud/deployment_test.go | 2 +- cmd/cloud/organization_test.go | 2 +- cmd/cloud/workspace.go | 28 ++++----- cmd/cloud/workspace_test.go | 4 +- 12 files changed, 87 insertions(+), 109 deletions(-) diff --git a/astro-client-iam-core/client.go b/astro-client-iam-core/client.go index a405e5c78..175b5db0a 100644 --- a/astro-client-iam-core/client.go +++ b/astro-client-iam-core/client.go @@ -6,13 +6,13 @@ import ( "encoding/json" "errors" "fmt" - "github.com/astronomer/astro-cli/context" - "github.com/astronomer/astro-cli/version" "net/http" "net/url" "runtime" + "github.com/astronomer/astro-cli/context" "github.com/astronomer/astro-cli/pkg/httputil" + "github.com/astronomer/astro-cli/version" ) var ( diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index d0f685188..a4c4cfede 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -4,15 +4,15 @@ import ( httpContext "context" "errors" "fmt" - astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" - "github.com/astronomer/astro-cli/cloud/organization" - workspace2 "github.com/astronomer/astro-cli/cloud/workspace-token" "io" "os" "strconv" "time" astrocore "github.com/astronomer/astro-cli/astro-client-core" + astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" + "github.com/astronomer/astro-cli/cloud/organization" + workspace2 "github.com/astronomer/astro-cli/cloud/workspace-token" "github.com/astronomer/astro-cli/context" "github.com/astronomer/astro-cli/pkg/ansi" "github.com/astronomer/astro-cli/pkg/input" @@ -126,8 +126,8 @@ func UpdateToken(id, name, newName, description, role, deployment string, out io tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ "DEPLOYMENT", } - organization := ctx.Organization - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) + organizationID := ctx.Organization + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -181,8 +181,8 @@ func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Wr tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ "DEPLOYMENT", } - organization := ctx.Organization - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) + organizationID := ctx.Organization + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -225,13 +225,13 @@ func DeleteToken(id, name, deployment string, force bool, out io.Writer, client return err } - organization := ctx.Organization + organizationID := ctx.Organization tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ "DEPLOYMENT", } - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -247,7 +247,7 @@ func DeleteToken(id, name, deployment string, force bool, out io.Writer, client } } - resp, err := client.DeleteDeploymentApiTokenWithResponse(httpContext.Background(), ctx.Organization, deployment, apiTokenID) + resp, err := client.DeleteDeploymentApiTokenWithResponse(httpContext.Background(), organizationID, deployment, apiTokenID) if err != nil { return err } @@ -398,7 +398,7 @@ func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astro return *resp.JSON200, nil } -func GetDeploymentTokenFromInputOrUser(id, name, deployment, organization string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { if id == "" { tokens, err := getDeploymentTokens(deployment, tokenTypes, client) if err != nil { @@ -409,12 +409,12 @@ func GetDeploymentTokenFromInputOrUser(id, name, deployment, organization string if err != nil { return token, err } - token, err = getTokenByID(tokenFromList.Id, organization, iamClient) + token, err = getTokenByID(tokenFromList.Id, organizationID, iamClient) if err != nil { return token, err } } else { - token, err = getTokenByID(id, organization, iamClient) + token, err = getTokenByID(id, organizationID, iamClient) if err != nil { return token, err } @@ -427,11 +427,11 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl if err != nil { return err } - organization := ctx.Organization + organizationID := ctx.Organization tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ "ORGANIZATION", } - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -475,7 +475,7 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl Description: token.Description, Roles: updateOrganizationAPITokenRoles, } - resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), organizationID, apiTokenID, updateOrganizationAPITokenRequest) if err != nil { return err } @@ -487,13 +487,13 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl return nil } -func RemoveWorkspaceTokenDeploymentRole(id, name, workspace string, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func RemoveWorkspaceTokenDeploymentRole(id, name, workspace, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - organization := ctx.Organization + organizationID := ctx.Organization if workspace == "" { workspace = ctx.Workspace @@ -501,7 +501,7 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace string, deployment s tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ "WORKSPACE", } - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -537,7 +537,7 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace string, deployment s Roles: &updateWorkspaceAPITokenRoles, } - resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID, updateWorkspaceAPITokenRequest) + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID, updateWorkspaceAPITokenRequest) if err != nil { return err } @@ -555,7 +555,7 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o return err } - organization := ctx.Organization + organizationID := ctx.Organization if workspace == "" { workspace = ctx.Workspace @@ -564,13 +564,16 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o var token astrocoreiam.ApiToken if operation == "create" { tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} - token, err = workspace2.GetTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) + token, err = workspace2.GetTokenFromInputOrUser(id, name, workspace, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } } else { tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{"WORKSPACE"} - token, err = GetDeploymentTokenFromInputOrUser(id, name, deployment, organization, &tokenTypes, client, iamClient) + token, err = GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) + if err != nil { + return err + } } apiTokenID := token.Id @@ -612,7 +615,7 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o Roles: &updateWorkspaceAPITokenRoles, } - resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID, updateWorkspaceAPITokenRequest) + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID, updateWorkspaceAPITokenRequest) if err != nil { return err } diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 35367b4bd..f5c2f87e7 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -3,8 +3,6 @@ package deployment import ( "bytes" "encoding/json" - astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" - astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "net/http" "os" "testing" @@ -12,6 +10,8 @@ import ( astrocore "github.com/astronomer/astro-cli/astro-client-core" astrocore_mocks "github.com/astronomer/astro-cli/astro-client-core/mocks" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" testUtil "github.com/astronomer/astro-cli/pkg/testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -25,12 +25,12 @@ var ( fullName2 = "User 2" token = "token" - iamApiToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &iamApiToken, + JSON200: &iamAPIToken, } errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index e431ea3df..0b71e0189 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -4,13 +4,13 @@ import ( httpContext "context" "errors" "fmt" - astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" "io" "os" "strconv" "time" astrocore "github.com/astronomer/astro-cli/astro-client-core" + astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" "github.com/astronomer/astro-cli/cloud/user" "github.com/astronomer/astro-cli/context" "github.com/astronomer/astro-cli/pkg/ansi" @@ -23,7 +23,6 @@ var ( errInvalidOrganizationTokenKey = errors.New("invalid Organization API token selection") errOrganizationTokenNotFound = errors.New("organization token specified was not found") errOrgTokenInWorkspace = errors.New("this Organization API token has already been added to the Workspace with that role") - errOrgTokenInDeployment = errors.New("this Organization API token has already been added to the Deployment with that role") ) const ( diff --git a/cloud/organization/organization_token_test.go b/cloud/organization/organization_token_test.go index 6fb0b590a..522552568 100644 --- a/cloud/organization/organization_token_test.go +++ b/cloud/organization/organization_token_test.go @@ -3,8 +3,6 @@ package organization import ( "bytes" "encoding/json" - astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" - astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "net/http" "os" "testing" @@ -12,6 +10,8 @@ import ( astrocore "github.com/astronomer/astro-cli/astro-client-core" astrocore_mocks "github.com/astronomer/astro-cli/astro-client-core/mocks" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "github.com/astronomer/astro-cli/cloud/user" testUtil "github.com/astronomer/astro-cli/pkg/testing" "github.com/stretchr/testify/assert" @@ -25,12 +25,12 @@ var ( fullName2 = "User 2" token = "token" workspaceID = "ck05r3bor07h40d02y2hw4n4v" - iamApiToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSAPCE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSAPCE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &iamApiToken, + JSON200: &iamAPIToken, } errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", diff --git a/cloud/workspace-token/workspace_token.go b/cloud/workspace-token/workspace_token.go index ac70cee45..6a0d2d80a 100644 --- a/cloud/workspace-token/workspace_token.go +++ b/cloud/workspace-token/workspace_token.go @@ -1,11 +1,9 @@ -package workspace_token +package workspacetoken import ( httpContext "context" "errors" "fmt" - "github.com/astronomer/astro-cli/cloud/organization" - workspace2 "github.com/astronomer/astro-cli/cloud/workspace" "io" "os" "strconv" @@ -13,7 +11,9 @@ import ( astrocore "github.com/astronomer/astro-cli/astro-client-core" astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" + "github.com/astronomer/astro-cli/cloud/organization" "github.com/astronomer/astro-cli/cloud/user" + workspace2 "github.com/astronomer/astro-cli/cloud/workspace" "github.com/astronomer/astro-cli/context" "github.com/astronomer/astro-cli/pkg/ansi" "github.com/astronomer/astro-cli/pkg/input" @@ -143,11 +143,11 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. workspace = ctx.Workspace } - organization := ctx.Organization + organizationID := ctx.Organization tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} - token, err := GetTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) + token, err := GetTokenFromInputOrUser(id, name, workspace, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -209,7 +209,7 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. UpdateWorkspaceAPITokenRequest.Roles.Workspace = &role } - resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID, UpdateWorkspaceAPITokenRequest) + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID, UpdateWorkspaceAPITokenRequest) if err != nil { return err } @@ -230,10 +230,10 @@ func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Wri if workspace == "" { workspace = ctx.Workspace } - organization := ctx.Organization + organizationID := ctx.Organization tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} - token, err := GetTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) + token, err := GetTokenFromInputOrUser(id, name, workspace, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -249,7 +249,7 @@ func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Wri return nil } } - resp, err := client.RotateWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID) + resp, err := client.RotateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID) if err != nil { return err } @@ -278,8 +278,8 @@ func DeleteToken(id, name, workspace string, force bool, out io.Writer, client a if workspace == "" { workspace = ctx.Workspace } - organization := ctx.Organization - token, err := GetTokenFromInputOrUser(id, name, workspace, organization, nil, client, iamClient) + organizationID := ctx.Organization + token, err := GetTokenFromInputOrUser(id, name, workspace, organizationID, nil, client, iamClient) if err != nil { return err } @@ -307,7 +307,7 @@ func DeleteToken(id, name, workspace string, force bool, out io.Writer, client a } } - resp, err := client.DeleteWorkspaceApiTokenWithResponse(httpContext.Background(), organization, workspace, apiTokenID) + resp, err := client.DeleteWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID) if err != nil { return err } @@ -464,7 +464,7 @@ func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astro return *resp.JSON200, nil } -func GetTokenFromInputOrUser(id, name, workspace, organization string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func GetTokenFromInputOrUser(id, name, workspace, organizationID string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { if id == "" { tokens, err := getWorkspaceTokens(workspace, tokenTypes, client) if err != nil { @@ -474,12 +474,12 @@ func GetTokenFromInputOrUser(id, name, workspace, organization string, tokenType if err != nil { return token, err } - token, err = getTokenByID(tokenFromList.Id, organization, iamClient) + token, err = getTokenByID(tokenFromList.Id, organizationID, iamClient) if err != nil { return token, err } } else { - token, err = getTokenByID(id, organization, iamClient) + token, err = getTokenByID(id, organizationID, iamClient) if err != nil { return token, err } @@ -497,11 +497,11 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie workspace = ctx.Workspace } - organization := ctx.Organization + organizationID := ctx.Organization tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{ "ORGANIZATION", } - token, err := GetWorkspaceTokenFromInputOrUser(id, name, workspace, organization, &tokenTypes, client, iamClient) + token, err := GetTokenFromInputOrUser(id, name, workspace, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -516,7 +516,7 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie continue // this removes the role in question } - if roles[i].EntityId == ctx.Organization { + if roles[i].EntityId == organizationID { orgRole = roles[i].Role } @@ -545,7 +545,7 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie Description: token.Description, Roles: updateOrganizationAPITokenRoles, } - resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), ctx.Organization, apiTokenID, updateOrganizationAPITokenRequest) + resp, err := client.UpdateOrganizationApiTokenWithResponse(httpContext.Background(), organizationID, apiTokenID, updateOrganizationAPITokenRequest) if err != nil { return err } @@ -557,30 +557,6 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie return nil } -func GetWorkspaceTokenFromInputOrUser(id, name, workspace, organization string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { - if id == "" { - tokens, err := getWorkspaceTokens(workspace, tokenTypes, client) - if err != nil { - return token, err - } - tokenFromList, err := getWorkspaceToken(id, name, workspace, "\nPlease select the Organization API token you would like to update:", tokens) - - if err != nil { - return token, err - } - token, err = getTokenByID(tokenFromList.Id, organization, iamClient) - if err != nil { - return token, err - } - } else { - token, err = getTokenByID(id, organization, iamClient) - if err != nil { - return token, err - } - } - return token, err -} - func UpsertOrgTokenWorkspaceRole(id, name, role, workspace, operation string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { diff --git a/cloud/workspace-token/workspace_token_test.go b/cloud/workspace-token/workspace_token_test.go index 33a0da1bd..81eb9d71a 100644 --- a/cloud/workspace-token/workspace_token_test.go +++ b/cloud/workspace-token/workspace_token_test.go @@ -1,11 +1,8 @@ -package workspace_token +package workspacetoken import ( "bytes" "encoding/json" - astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" - astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" - "github.com/astronomer/astro-cli/cloud/workspace" "net/http" "os" "testing" @@ -13,7 +10,10 @@ import ( astrocore "github.com/astronomer/astro-cli/astro-client-core" astrocore_mocks "github.com/astronomer/astro-cli/astro-client-core/mocks" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "github.com/astronomer/astro-cli/cloud/user" + "github.com/astronomer/astro-cli/cloud/workspace" testUtil "github.com/astronomer/astro-cli/pkg/testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -26,12 +26,12 @@ var ( fullName1 = "User 1" fullName2 = "User 2" token = "token" - iamApiToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &iamApiToken, + JSON200: &iamAPIToken, } errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", diff --git a/cmd/cloud/deployment.go b/cmd/cloud/deployment.go index ab3700591..f3496d94a 100644 --- a/cmd/cloud/deployment.go +++ b/cmd/cloud/deployment.go @@ -1075,7 +1075,7 @@ func newCreateOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { }, } cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") - cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Deployment role to grant to the "+ + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Deployment role to add to the "+ "Organization API token. Possible values are DEPLOYMENT_ADMIN or a custom role name.") return cmd } @@ -1090,7 +1090,7 @@ func newUpdateOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { }, } cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to update in a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") - cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Deployment role to grant to the "+ + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Deployment role to update the "+ "Organization API token. Possible values are DEPLOYMENT_ADMIN or a custom role name.") return cmd } @@ -1259,7 +1259,7 @@ func newListOrganizationTokensInDeployment(out io.Writer) *cobra.Command { Short: "List all Organization API tokens in a deployment", Long: "List all Organization API tokens in a deployment\n$astro deployment token organization-token list", RunE: func(cmd *cobra.Command, args []string) error { - return listOrganizationTokensInDeployment(cmd, args, out) + return listOrganizationTokensInDeployment(cmd, out) }, } return cmd @@ -1271,13 +1271,13 @@ func newListWorkspaceTokensInDeployment(out io.Writer) *cobra.Command { Short: "List all Workspace API tokens in a deployment", Long: "List all Workspace API tokens in a deployment\n$astro deployment token workspace-token list", RunE: func(cmd *cobra.Command, args []string) error { - return listWorkspaceTokensInDeployment(cmd, args, out) + return listWorkspaceTokensInDeployment(cmd, out) }, } return cmd } -func listOrganizationTokensInDeployment(cmd *cobra.Command, args []string, out io.Writer) error { +func listOrganizationTokensInDeployment(cmd *cobra.Command, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } @@ -1290,7 +1290,7 @@ func listOrganizationTokensInDeployment(cmd *cobra.Command, args []string, out i return deployment.ListTokens(astroCoreClient, deploymentID, &tokenTypes, out) } -func listWorkspaceTokensInDeployment(cmd *cobra.Command, args []string, out io.Writer) error { +func listWorkspaceTokensInDeployment(cmd *cobra.Command, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } diff --git a/cmd/cloud/deployment_test.go b/cmd/cloud/deployment_test.go index c454b3e24..7a9bdb63e 100644 --- a/cmd/cloud/deployment_test.go +++ b/cmd/cloud/deployment_test.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "fmt" - astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "io" "net/http" "os" @@ -14,6 +13,7 @@ import ( airflowversions "github.com/astronomer/astro-cli/airflow_versions" astrocore "github.com/astronomer/astro-cli/astro-client-core" astrocore_mocks "github.com/astronomer/astro-cli/astro-client-core/mocks" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" astroplatformcore "github.com/astronomer/astro-cli/astro-client-platform-core" astroplatformcore_mocks "github.com/astronomer/astro-cli/astro-client-platform-core/mocks" diff --git a/cmd/cloud/organization_test.go b/cmd/cloud/organization_test.go index 2d710415a..1caeef852 100644 --- a/cmd/cloud/organization_test.go +++ b/cmd/cloud/organization_test.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "fmt" - astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" "io" "net/http" "os" @@ -12,6 +11,7 @@ import ( "testing" "time" + astroiamcore_mocks "github.com/astronomer/astro-cli/astro-client-iam-core/mocks" astroplatformcore "github.com/astronomer/astro-cli/astro-client-platform-core" astrocore "github.com/astronomer/astro-cli/astro-client-core" diff --git a/cmd/cloud/workspace.go b/cmd/cloud/workspace.go index 037ca971b..1f676c9db 100644 --- a/cmd/cloud/workspace.go +++ b/cmd/cloud/workspace.go @@ -2,17 +2,17 @@ package cloud import ( "fmt" - astrocore "github.com/astronomer/astro-cli/astro-client-core" - "github.com/astronomer/astro-cli/cloud/workspace-token" "io" "os" "strconv" "strings" + astrocore "github.com/astronomer/astro-cli/astro-client-core" "github.com/astronomer/astro-cli/cloud/organization" "github.com/astronomer/astro-cli/cloud/team" "github.com/astronomer/astro-cli/cloud/user" "github.com/astronomer/astro-cli/cloud/workspace" + "github.com/astronomer/astro-cli/cloud/workspace-token" "github.com/astronomer/astro-cli/pkg/input" "github.com/astronomer/astro-cli/pkg/printutil" @@ -418,7 +418,7 @@ func newUpdateOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { }, } cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to update in a Workspace. If the name contains a space, specify the entire name within quotes \"\" ") - cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Workspace role to grant to the "+ + cmd.Flags().StringVarP(&tokenRole, "role", "r", "", "The Workspace role to update the "+ "Organization API token. Possible values are"+allowedWorkspaceRoleNamesProse) return cmd } @@ -435,7 +435,7 @@ func createOrgTokenWorkspaceRole(cmd *cobra.Command, args []string, out io.Write } cmd.SilenceUsage = true - return workspace_token.UpsertOrgTokenWorkspaceRole(orgTokenID, orgTokenName, tokenRole, workspaceID, "create", out, astroCoreClient, astroCoreIamClient) + return workspacetoken.UpsertOrgTokenWorkspaceRole(orgTokenID, orgTokenName, tokenRole, workspaceID, "create", out, astroCoreClient, astroCoreIamClient) } func updateOrgTokenWorkspaceRole(cmd *cobra.Command, args []string, out io.Writer) error { @@ -450,7 +450,7 @@ func updateOrgTokenWorkspaceRole(cmd *cobra.Command, args []string, out io.Write } cmd.SilenceUsage = true - return workspace_token.UpsertOrgTokenWorkspaceRole(orgTokenID, orgTokenName, tokenRole, workspaceID, "update", out, astroCoreClient, astroCoreIamClient) + return workspacetoken.UpsertOrgTokenWorkspaceRole(orgTokenID, orgTokenName, tokenRole, workspaceID, "update", out, astroCoreClient, astroCoreIamClient) } func newRemoveOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { @@ -474,7 +474,7 @@ func removeWorkspaceTokenFromDeploymentRole(cmd *cobra.Command, args []string, o } cmd.SilenceUsage = true - return workspace_token.RemoveOrgTokenWorkspaceRole(orgTokenID, orgTokenName, workspaceID, out, astroCoreClient, astroCoreIamClient) + return workspacetoken.RemoveOrgTokenWorkspaceRole(orgTokenID, orgTokenName, workspaceID, out, astroCoreClient, astroCoreIamClient) } func newListOrganizationTokensInWorkspace(out io.Writer) *cobra.Command { @@ -483,18 +483,18 @@ func newListOrganizationTokensInWorkspace(out io.Writer) *cobra.Command { Short: "List all Organization API tokens in a workspace", Long: "List all Organization API tokens in a workspace\n$astro workspace token organization-token list", RunE: func(cmd *cobra.Command, args []string) error { - return listOrganizationTokensInWorkspace(cmd, args, out) + return listOrganizationTokensInWorkspace(cmd, out) }, } return cmd } -func listOrganizationTokensInWorkspace(cmd *cobra.Command, args []string, out io.Writer) error { +func listOrganizationTokensInWorkspace(cmd *cobra.Command, out io.Writer) error { cmd.SilenceUsage = true tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{ "ORGANIZATION", } - return workspace_token.ListTokens(astroCoreClient, deploymentID, &tokenTypes, out) + return workspacetoken.ListTokens(astroCoreClient, deploymentID, &tokenTypes, out) } func newWorkspaceTeamRemoveCmd(out io.Writer) *cobra.Command { @@ -683,7 +683,7 @@ func removeWorkspaceUser(cmd *cobra.Command, args []string, out io.Writer) error func listWorkspaceToken(cmd *cobra.Command, out io.Writer) error { cmd.SilenceUsage = true - return workspace_token.ListTokens(astroCoreClient, workspaceID, nil, out) + return workspacetoken.ListTokens(astroCoreClient, workspaceID, nil, out) } func createWorkspaceToken(cmd *cobra.Command, out io.Writer) error { @@ -702,7 +702,7 @@ func createWorkspaceToken(cmd *cobra.Command, out io.Writer) error { } cmd.SilenceUsage = true - return workspace_token.CreateToken(tokenName, tokenDescription, tokenRole, workspaceID, tokenExpiration, cleanTokenOutput, out, astroCoreClient) + return workspacetoken.CreateToken(tokenName, tokenDescription, tokenRole, workspaceID, tokenExpiration, cleanTokenOutput, out, astroCoreClient) } func updateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -713,7 +713,7 @@ func updateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro } cmd.SilenceUsage = true - return workspace_token.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, workspaceID, out, astroCoreClient, astroCoreIamClient) + return workspacetoken.UpdateToken(tokenID, name, tokenName, tokenDescription, tokenRole, workspaceID, out, astroCoreClient, astroCoreIamClient) } func rotateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -723,7 +723,7 @@ func rotateWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro tokenID = strings.ToLower(args[0]) } cmd.SilenceUsage = true - return workspace_token.RotateToken(tokenID, name, workspaceID, cleanTokenOutput, forceRotate, out, astroCoreClient, astroCoreIamClient) + return workspacetoken.RotateToken(tokenID, name, workspaceID, cleanTokenOutput, forceRotate, out, astroCoreClient, astroCoreIamClient) } func deleteWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) error { @@ -734,7 +734,7 @@ func deleteWorkspaceToken(cmd *cobra.Command, args []string, out io.Writer) erro } cmd.SilenceUsage = true - return workspace_token.DeleteToken(tokenID, name, workspaceID, forceDelete, out, astroCoreClient, astroCoreIamClient) + return workspacetoken.DeleteToken(tokenID, name, workspaceID, forceDelete, out, astroCoreClient, astroCoreIamClient) } func addOrgTokenToWorkspace(cmd *cobra.Command, args []string, out io.Writer) error { diff --git a/cmd/cloud/workspace_test.go b/cmd/cloud/workspace_test.go index ab7cd2235..9279ab659 100644 --- a/cmd/cloud/workspace_test.go +++ b/cmd/cloud/workspace_test.go @@ -1031,12 +1031,12 @@ var ( apiToken1, {Id: "token2", Name: "Token 2", Description: description2, Type: "Type 2", Roles: []astrocore.ApiTokenRole{{EntityId: mockWorkspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, } - iamApiToken = astroiamcore.ApiToken{Id: "token1", Name: tokenName1, Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: mockWorkspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: tokenName1, Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: mockWorkspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &iamApiToken, + JSON200: &iamAPIToken, } errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", From 1dbdd11d1bd3dd27a6337f6a8ca5356bbf2f7238 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 14:29:14 -0400 Subject: [PATCH 10/26] lint --- cloud/deployment/deployment_token.go | 1 - cloud/organization/organization_token.go | 1 - cmd/cloud/workspace.go | 2 +- 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index a4c4cfede..8f5a69d0c 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -405,7 +405,6 @@ func GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID stri return token, err } tokenFromList, err := getDeploymentToken(id, name, deployment, "\nPlease select the Organization API token you would like to update:", tokens) - if err != nil { return token, err } diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index 0b71e0189..586c785b2 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -282,7 +282,6 @@ func GetTokenFromInputOrUser(id, name, organization string, client astrocore.Cor return token, err } tokenFromList, err := getOrganizationToken(id, name, "\nPlease select the Organization API token you would like to update:", tokens) - if err != nil { return token, err } diff --git a/cmd/cloud/workspace.go b/cmd/cloud/workspace.go index 1f676c9db..e6b359443 100644 --- a/cmd/cloud/workspace.go +++ b/cmd/cloud/workspace.go @@ -12,7 +12,7 @@ import ( "github.com/astronomer/astro-cli/cloud/team" "github.com/astronomer/astro-cli/cloud/user" "github.com/astronomer/astro-cli/cloud/workspace" - "github.com/astronomer/astro-cli/cloud/workspace-token" + workspacetoken "github.com/astronomer/astro-cli/cloud/workspace-token" "github.com/astronomer/astro-cli/pkg/input" "github.com/astronomer/astro-cli/pkg/printutil" From 244ad7bda39efdfe7ce7ecf65e65869882c26f4d Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 16:35:12 -0400 Subject: [PATCH 11/26] add unit tests for new cloud client methods --- cloud/deployment/deployment_token.go | 8 +- cloud/deployment/deployment_token_test.go | 686 ++++++++++++++++++ cloud/workspace-token/workspace_token.go | 2 +- cloud/workspace-token/workspace_token_test.go | 362 ++++++++- 4 files changed, 1051 insertions(+), 7 deletions(-) diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index 8f5a69d0c..ff43be1e9 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -482,7 +482,7 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl if err != nil { return err } - fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) + fmt.Fprintf(out, "Astro Organization API token %s was successfully removed from the Deployment\n", token.Name) return nil } @@ -544,7 +544,7 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace, deployment string, if err != nil { return err } - fmt.Fprintf(out, "Astro Workspace API token %s was successfully added to the Deployment\n", token.Name) + fmt.Fprintf(out, "Astro Workspace API token %s was successfully removed from the Deployment\n", token.Name) return nil } @@ -622,7 +622,7 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o if err != nil { return err } - fmt.Fprintf(out, "Astro Workspace API token %s was successfully added to the Deployment\n", token.Name) + fmt.Fprintf(out, "Astro Workspace API token %s was successfully added/updated to the Deployment\n", token.Name) return nil } @@ -701,6 +701,6 @@ func UpsertOrgTokenDeploymentRole(id, name, role, deployment, operation string, if err != nil { return err } - fmt.Fprintf(out, "Astro Organization API token %s was successfully added to the Deployment\n", token.Name) + fmt.Fprintf(out, "Astro Organization API token %s was successfully added/updated to the Deployment\n", token.Name) return nil } diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index f5c2f87e7..9d7523ff9 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -139,6 +139,72 @@ var ( }, Body: errorBodyUpdate, } + UpdateOrganizationAPITokenResponseOK = astrocore.UpdateOrganizationApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &apiToken1, + } + + UpdateOrganizationAPITokenResponseError = astrocore.UpdateOrganizationApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 500, + }, + Body: errorBodyUpdate, + JSON200: nil, + } + + UpdateWorkspaceAPITokenResponseOK = astrocore.UpdateWorkspaceApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &apiToken1, + } + + UpdateWorkspaceAPITokenResponseError = astrocore.UpdateWorkspaceApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 500, + }, + Body: errorBodyUpdate, + JSON200: nil, + } + + ListOrganizationAPITokensResponseOK = astrocore.ListOrganizationApiTokensResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &astrocore.ListApiTokensPaginated{ + ApiTokens: apiTokens, + Limit: 1, + Offset: 0, + }, + } + ListOrganizationAPITokensResponseError = astrocore.ListOrganizationApiTokensResponse{ + HTTPResponse: &http.Response{ + StatusCode: 500, + }, + Body: errorBodyList, + JSON200: nil, + } + + ListWorkspaceAPITokensResponseOK = astrocore.ListWorkspaceApiTokensResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &astrocore.ListApiTokensPaginated{ + ApiTokens: apiTokens, + Limit: 1, + Offset: 0, + }, + } + + ListWorkspaceAPITokensResponseError = astrocore.ListWorkspaceApiTokensResponse{ + HTTPResponse: &http.Response{ + StatusCode: 500, + }, + Body: errorBodyList, + JSON200: nil, + } ) func TestListTokens(t *testing.T) { @@ -629,3 +695,623 @@ func TestTimeAgo(t *testing.T) { assert.Equal(t, "10 days ago", result) }) } + +func TestRemoveOrgTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token Token 1 was successfully removed from the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenDeploymentRole("", "", "", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListDeploymentApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenDeploymentRole("", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("error on GetApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenDeploymentRole("", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) + + t.Run("error on UpdateOrganizationApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenDeploymentRole("", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to update token") + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token Token 1 was successfully removed from the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenDeploymentRole("token-id", "", "", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on GetApiTokenWithResponse with token id passed in", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenDeploymentRole("token-id", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) +} + +func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + expectedOutMessage := "Astro Workspace API token Token 1 was successfully removed from the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveWorkspaceTokenDeploymentRole("", "", "", "", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListDeploymentApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveWorkspaceTokenDeploymentRole("", "", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("error on GetApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveWorkspaceTokenDeploymentRole("", "", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) + + t.Run("error on UpdateWorkspaceApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseError, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveWorkspaceTokenDeploymentRole("", "", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to update token") + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + expectedOutMessage := "Astro Workspace API token Token 1 was successfully removed from the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveWorkspaceTokenDeploymentRole("token-id", "", "", "", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on GetApiTokenWithResponse with token id passed in", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveWorkspaceTokenDeploymentRole("token-id", "", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) +} + +func TestUpsertOrgTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path Create", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token Token 1 was successfully added/updated to the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("", "", "", "", "create", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListOrganizationApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("happy path Update", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token Token 1 was successfully added/updated to the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("", "", "", "", "update", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListDeploymentApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("", "", "", "", "update", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("error on GetApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) + + t.Run("error on UpdateOrganizationApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to update token") + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token Token 1 was successfully added/updated to the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("token-id", "", "", "", "create", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on GetApiTokenWithResponse with token id passed in", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("token-id", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) +} + +func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path Create", func(t *testing.T) { + expectedOutMessage := "Astro Workspace API token Token 1 was successfully added/updated to the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "create", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListWorkspaceApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("happy path Update", func(t *testing.T) { + expectedOutMessage := "Astro Workspace API token Token 1 was successfully added/updated to the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "update", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListDeploymentApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "update", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("error on GetApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) + + t.Run("error on UpdateWorkspaceApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseError, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to update token") + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + expectedOutMessage := "Astro Workspace API token Token 1 was successfully added/updated to the Deployment\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("token-id", "", "", "", "", "create", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on GetApiTokenWithResponse with token id passed in", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("token-id", "", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) +} diff --git a/cloud/workspace-token/workspace_token.go b/cloud/workspace-token/workspace_token.go index 6a0d2d80a..249d59ef5 100644 --- a/cloud/workspace-token/workspace_token.go +++ b/cloud/workspace-token/workspace_token.go @@ -553,7 +553,7 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie if err != nil { return err } - fmt.Fprintf(out, "Astro Organization API token %s was successfully removed from the Deployment\n", token.Name) + fmt.Fprintf(out, "Astro Organization API token %s was successfully removed from the Workspace\n", token.Name) return nil } diff --git a/cloud/workspace-token/workspace_token_test.go b/cloud/workspace-token/workspace_token_test.go index 81eb9d71a..862dd3979 100644 --- a/cloud/workspace-token/workspace_token_test.go +++ b/cloud/workspace-token/workspace_token_test.go @@ -72,14 +72,14 @@ var ( Offset: 0, }, } - errorBodyList, _ = json.Marshal(astrocore.Error{ + errorBodyListTokens, _ = json.Marshal(astrocore.Error{ Message: "failed to list tokens", }) ListWorkspaceAPITokensResponseError = astrocore.ListWorkspaceApiTokensResponse{ HTTPResponse: &http.Response{ StatusCode: 500, }, - Body: errorBodyList, + Body: errorBodyListTokens, JSON200: nil, } CreateWorkspaceAPITokenResponseOK = astrocore.CreateWorkspaceApiTokenResponse{ @@ -89,6 +89,54 @@ var ( JSON200: &apiToken1, } + orgAPIToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "ORGANIZATION_MEMBER"}, {EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} + orgAPIToken2 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} + + orgAPITokens = []astrocore.ApiToken{ + orgAPIToken1, + orgAPIToken2, + } + + ListOrganizationAPITokensResponseOK = astrocore.ListOrganizationApiTokensResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &astrocore.ListApiTokensPaginated{ + ApiTokens: orgAPITokens, + Limit: 1, + Offset: 0, + }, + } + + errorBodyList, _ = json.Marshal(astrocore.Error{ + Message: "failed to list tokens", + }) + ListOrganizationAPITokensResponseError = astrocore.ListOrganizationApiTokensResponse{ + HTTPResponse: &http.Response{ + StatusCode: 500, + }, + Body: errorBodyList, + JSON200: nil, + } + + UpdateOrganizationAPITokenResponseOK = astrocore.UpdateOrganizationApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &orgAPIToken1, + } + + errorBodyUpdateToken, _ = json.Marshal(astrocore.Error{ + Message: "failed to update token", + }) + UpdateOrganizationAPITokenResponseError = astrocore.UpdateOrganizationApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 500, + }, + Body: errorBodyUpdateToken, + JSON200: nil, + } + errorBodyCreate, _ = json.Marshal(astrocore.Error{ Message: "failed to create workspace token", }) @@ -621,3 +669,313 @@ func TestTimeAgo(t *testing.T) { assert.Equal(t, "10 days ago", result) }) } + +func TestUpsertOrgTokenWorkspaceRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path Create", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token token1 was successfully added/updated to the Workspace\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("", "", "", "", "create", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListOrganizationApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("happy path Update", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token token1 was successfully added/updated to the Workspace\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("", "", "", "", "update", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListWorkspaceApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("", "", "", "", "update", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("error on GetApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) + + t.Run("error on UpdateOrganizationApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to update token") + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token token1 was successfully added/updated to the Workspace\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("token-id", "", "", "", "create", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on GetApiTokenWithResponse with token id passed in", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("token-id", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) +} + +func TestRemoveOrgTokenWorkspaceRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token token1 was successfully removed from the Workspace\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenWorkspaceRole("", "", "", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on ListWorkspaceApiTokensWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenWorkspaceRole("", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to list tokens") + }) + + t.Run("error on GetApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenWorkspaceRole("", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) + + t.Run("error on UpdateOrganizationApiTokenWithResponse", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenWorkspaceRole("", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to update token") + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + expectedOutMessage := "Astro Organization API token token1 was successfully removed from the Workspace\n" + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenWorkspaceRole("token-id", "", "", out, mockClient, mockIamClient) + assert.NoError(t, err) + assert.Equal(t, expectedOutMessage, out.String()) + }) + + t.Run("error on GetApiTokenWithResponse with token id passed in", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseError, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = RemoveOrgTokenWorkspaceRole("token-id", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "failed to get token") + }) +} From 956fbf755394fa79bf93fa506823710cc68742c8 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 17:10:25 -0400 Subject: [PATCH 12/26] increase test coverage --- cloud/deployment/deployment_token_test.go | 2 +- cloud/organization/organization_token_test.go | 2 +- cloud/workspace-token/workspace_token_test.go | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 9d7523ff9..49bfda41e 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -46,7 +46,7 @@ var ( apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: []astrocore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} apiTokens = []astrocore.ApiToken{ apiToken1, - {Id: "token2", Name: "Token 2", Description: description2, Type: "ORGANIZATION", Roles: []astrocore.ApiTokenRole{{EntityId: "otherDeployment", EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{ApiTokenName: &fullName2}}, + {Id: "token2", Name: "Token 2", Description: description2, Type: "ORGANIZATION", Roles: []astrocore.ApiTokenRole{{EntityId: "otherDeployment", EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_MEMBER"}, {EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{ApiTokenName: &fullName2}}, } apiTokens2 = []astrocore.ApiToken{ apiToken1, diff --git a/cloud/organization/organization_token_test.go b/cloud/organization/organization_token_test.go index 522552568..ec70229bc 100644 --- a/cloud/organization/organization_token_test.go +++ b/cloud/organization/organization_token_test.go @@ -44,7 +44,7 @@ var ( } apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "ORGANIZATION_MEMBER"}, {EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} - apiToken2 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} + apiToken2 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_MEMBER"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} apiTokens = []astrocore.ApiToken{ apiToken1, diff --git a/cloud/workspace-token/workspace_token_test.go b/cloud/workspace-token/workspace_token_test.go index 862dd3979..4a2839a69 100644 --- a/cloud/workspace-token/workspace_token_test.go +++ b/cloud/workspace-token/workspace_token_test.go @@ -43,7 +43,7 @@ var ( Body: errorTokenGet, JSON200: nil, } - apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} + apiToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} apiTokens = []astrocore.ApiToken{ apiToken1, {Id: "token2", Name: "Token 2", Description: description2, Type: "ORGANIZATION", Roles: []astrocore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, @@ -90,7 +90,7 @@ var ( } orgAPIToken1 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "ORGANIZATION_MEMBER"}, {EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} - orgAPIToken2 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} + orgAPIToken2 = astrocore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: []astrocore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_MEMBER"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName1}} orgAPITokens = []astrocore.ApiToken{ orgAPIToken1, From 1da778654f4e72ba9d7d868ea4d71f000fc2a9fd Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 17:54:12 -0400 Subject: [PATCH 13/26] add test coverage for cmds --- cloud/workspace-token/workspace_token.go | 1 - cmd/cloud/deployment_test.go | 220 +++++++++++++++++++++++ cmd/cloud/workspace_test.go | 110 ++++++++++++ 3 files changed, 330 insertions(+), 1 deletion(-) diff --git a/cloud/workspace-token/workspace_token.go b/cloud/workspace-token/workspace_token.go index 249d59ef5..7eab7c09e 100644 --- a/cloud/workspace-token/workspace_token.go +++ b/cloud/workspace-token/workspace_token.go @@ -379,7 +379,6 @@ func getWorkspaceTokens(workspace string, tokenTypes *[]astrocore.ListWorkspaceA if workspace == "" { workspace = ctx.Workspace } - resp, err := client.ListWorkspaceApiTokensWithResponse(httpContext.Background(), ctx.Organization, workspace, &astrocore.ListWorkspaceApiTokensParams{TokenTypes: tokenTypes}) if err != nil { return []astrocore.ApiToken{}, err diff --git a/cmd/cloud/deployment_test.go b/cmd/cloud/deployment_test.go index 7a9bdb63e..8abd729e5 100644 --- a/cmd/cloud/deployment_test.go +++ b/cmd/cloud/deployment_test.go @@ -2422,3 +2422,223 @@ func TestDeploymentTokenDelete(t *testing.T) { assert.NoError(t, err) }) } + +func TestCreateWorkspaceTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path Create", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + + cmdArgs := []string{"token", "workspace-token", "create", "--deployment-id", mockDeploymentID, "--role", "DEPLOYMENT_ADMIN"} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "workspace-token", "create", "token-id", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestUpdateWorkspaceTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + + t.Run("happy path Update", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "workspace-token", "update", "--deployment-id", mockDeploymentID, "--role", "DEPLOYMENT_ADMIN"} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "workspace-token", "update", "token-id", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestCreateOrganizationTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path Create", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + + cmdArgs := []string{"token", "organization-token", "create", "--deployment-id", mockDeploymentID, "--role", "DEPLOYMENT_ADMIN"} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "create", "token-id", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestUpdateOrganizationTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + + t.Run("happy path Update", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "update", "--deployment-id", mockDeploymentID, "--role", "DEPLOYMENT_ADMIN"} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "update", "token-id", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "workspace-token", "remove", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "workspace-token", "remove", "token-id", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestRemoveOrganizationTokenDeploymentRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "remove", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "remove", "token-id", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestListOrganizationTokenDeploymentRoles(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "list", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestListWorkspaceTokenDeploymentRoles(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "workspace-token", "list", "--deployment-id", mockDeploymentID} + _, err := execDeploymentCmd(cmdArgs...) + assert.NoError(t, err) + }) +} diff --git a/cmd/cloud/workspace_test.go b/cmd/cloud/workspace_test.go index 9279ab659..c84e9d566 100644 --- a/cmd/cloud/workspace_test.go +++ b/cmd/cloud/workspace_test.go @@ -1628,3 +1628,113 @@ func TestWorkspaceTokenAdd(t *testing.T) { assert.NoError(t, err) }) } + +func TestCreateOrganizationTokenWorkspaceRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path Create", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + + cmdArgs := []string{"token", "organization-token", "create", "--role", "DEPLOYMENT_ADMIN"} + _, err := execWorkspaceCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "create", "token-id"} + _, err := execWorkspaceCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestUpdateOrganizationTokenWorkspaceRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + + t.Run("happy path Update", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "update", "--role", "DEPLOYMENT_ADMIN"} + _, err := execWorkspaceCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + // mock os.Stdin + defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "update", "token-id"} + _, err := execWorkspaceCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestRemoveOrganizationTokenWorkspaceRole(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "remove"} + _, err := execWorkspaceCmd(cmdArgs...) + assert.NoError(t, err) + }) + + t.Run("happy path with token id passed in", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "remove", "token-id"} + _, err := execWorkspaceCmd(cmdArgs...) + assert.NoError(t, err) + }) +} + +func TestListOrganizationTokenWorkspaceRoles(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + t.Run("happy path", func(t *testing.T) { + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() + defer testUtil.MockUserInput(t, "1")() + astroCoreClient = mockClient + astroCoreIamClient = mockIamClient + cmdArgs := []string{"token", "organization-token", "list"} + _, err := execWorkspaceCmd(cmdArgs...) + assert.NoError(t, err) + }) +} From e219260265a4dc4fa5d7877af6c82250b495f3fb Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 19:37:39 -0400 Subject: [PATCH 14/26] remove token name param from failing test --- cmd/cloud/workspace_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/cloud/workspace_test.go b/cmd/cloud/workspace_test.go index c84e9d566..061c1c3fb 100644 --- a/cmd/cloud/workspace_test.go +++ b/cmd/cloud/workspace_test.go @@ -1553,7 +1553,7 @@ func TestWorkspaceTokenAdd(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil) astroCoreClient = mockClient - cmdArgs := []string{"token", "add", "--org-token-name", tokenName1, "--role", "WORKSPACE_MEMBER"} + cmdArgs := []string{"token", "add", "--role", "WORKSPACE_MEMBER"} _, err := execWorkspaceCmd(cmdArgs...) assert.ErrorContains(t, err, "failed to list tokens") }) From 441979298f4783dc5673979d4ab46b2ce45449c5 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Mon, 8 Apr 2024 19:58:36 -0400 Subject: [PATCH 15/26] test fix --- cmd/cloud/workspace_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/cloud/workspace_test.go b/cmd/cloud/workspace_test.go index 061c1c3fb..5689a0635 100644 --- a/cmd/cloud/workspace_test.go +++ b/cmd/cloud/workspace_test.go @@ -1540,8 +1540,8 @@ var ( func TestWorkspaceTokenAdd(t *testing.T) { expectedHelp := "Add an Organization API token to an Astro Workspace" + orgTokenID = "" testUtil.InitTestConfig(testUtil.LocalPlatform) - t.Run("-h prints list help", func(t *testing.T) { cmdArgs := []string{"token", "add", "-h"} resp, err := execWorkspaceCmd(cmdArgs...) @@ -1553,7 +1553,7 @@ func TestWorkspaceTokenAdd(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseError, nil) astroCoreClient = mockClient - cmdArgs := []string{"token", "add", "--role", "WORKSPACE_MEMBER"} + cmdArgs := []string{"token", "add", "--org-token-name", tokenName1, "--role", "WORKSPACE_MEMBER"} _, err := execWorkspaceCmd(cmdArgs...) assert.ErrorContains(t, err, "failed to list tokens") }) From ea2a60a2b0a1c26911cd0c4850448a8c8f5c17eb Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 08:57:38 -0400 Subject: [PATCH 16/26] increase test coverage --- cloud/organization/organization_token_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cloud/organization/organization_token_test.go b/cloud/organization/organization_token_test.go index ec70229bc..814896c72 100644 --- a/cloud/organization/organization_token_test.go +++ b/cloud/organization/organization_token_test.go @@ -25,7 +25,7 @@ var ( fullName2 = "User 2" token = "token" workspaceID = "ck05r3bor07h40d02y2hw4n4v" - iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "ORGANIZATION", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSAPCE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, From bd24207c2e09e25a4d7afd6a2111bd2555d0a47e Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 09:08:26 -0400 Subject: [PATCH 17/26] increase test coverage --- cloud/deployment/deployment_token_test.go | 3 ++- cloud/organization/organization_token_test.go | 2 +- cloud/workspace-token/workspace_token_test.go | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 49bfda41e..5d53107d8 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -19,13 +19,14 @@ import ( var ( deploymentID = "ck05r3bor07h40d02y2hw4n4v" + workspaceID = "ck05r3bor07h40d02y2hw4n4w" description1 = "Description 1" description2 = "Description 2" fullName1 = "User 1" fullName2 = "User 2" token = "token" - iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: deploymentID, EntityType: "DEPLOYMENT", Role: "DEPLOYMENT_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, diff --git a/cloud/organization/organization_token_test.go b/cloud/organization/organization_token_test.go index 814896c72..359ce3329 100644 --- a/cloud/organization/organization_token_test.go +++ b/cloud/organization/organization_token_test.go @@ -25,7 +25,7 @@ var ( fullName2 = "User 2" token = "token" workspaceID = "ck05r3bor07h40d02y2hw4n4v" - iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, diff --git a/cloud/workspace-token/workspace_token_test.go b/cloud/workspace-token/workspace_token_test.go index 4a2839a69..61d635581 100644 --- a/cloud/workspace-token/workspace_token_test.go +++ b/cloud/workspace-token/workspace_token_test.go @@ -26,7 +26,7 @@ var ( fullName1 = "User 1" fullName2 = "User 2" token = "token" - iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: workspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, From 8c287ea757dcdbc614158d7d28b4b80c00880f7e Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 09:09:54 -0400 Subject: [PATCH 18/26] more test coverage --- cloud/deployment/deployment_token_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 5d53107d8..13f598a92 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -26,7 +26,7 @@ var ( fullName2 = "User 2" token = "token" - iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: deploymentID, Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, From 97ff13ca9f3cb0bb11cfeee967c94bed977d896f Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 09:23:33 -0400 Subject: [PATCH 19/26] increase test coverage --- cloud/deployment/deployment_token_test.go | 56 +++++++++++------------ 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 13f598a92..96e8c3096 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -718,7 +718,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveOrgTokenDeploymentRole("", "", "", out, mockClient, mockIamClient) + err = RemoveOrgTokenDeploymentRole("", "", deploymentID, out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -739,7 +739,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveOrgTokenDeploymentRole("", "", "", out, mockClient, mockIamClient) + err = RemoveOrgTokenDeploymentRole("", "", deploymentID, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -760,7 +760,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveOrgTokenDeploymentRole("", "", "", out, mockClient, mockIamClient) + err = RemoveOrgTokenDeploymentRole("", "", deploymentID, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) @@ -782,7 +782,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveOrgTokenDeploymentRole("", "", "", out, mockClient, mockIamClient) + err = RemoveOrgTokenDeploymentRole("", "", deploymentID, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to update token") }) @@ -804,7 +804,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveOrgTokenDeploymentRole("token-id", "", "", out, mockClient, mockIamClient) + err = RemoveOrgTokenDeploymentRole("token-id", "", deploymentID, out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -825,7 +825,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveOrgTokenDeploymentRole("token-id", "", "", out, mockClient, mockIamClient) + err = RemoveOrgTokenDeploymentRole("token-id", "", deploymentID, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) } @@ -851,7 +851,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveWorkspaceTokenDeploymentRole("", "", "", "", out, mockClient, mockIamClient) + err = RemoveWorkspaceTokenDeploymentRole("", "", "", deploymentID, out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -872,7 +872,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveWorkspaceTokenDeploymentRole("", "", "", "", out, mockClient, mockIamClient) + err = RemoveWorkspaceTokenDeploymentRole("", "", "", deploymentID, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -893,7 +893,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveWorkspaceTokenDeploymentRole("", "", "", "", out, mockClient, mockIamClient) + err = RemoveWorkspaceTokenDeploymentRole("", "", "", deploymentID, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) @@ -915,7 +915,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveWorkspaceTokenDeploymentRole("", "", "", "", out, mockClient, mockIamClient) + err = RemoveWorkspaceTokenDeploymentRole("", "", "", deploymentID, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to update token") }) @@ -937,7 +937,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveWorkspaceTokenDeploymentRole("token-id", "", "", "", out, mockClient, mockIamClient) + err = RemoveWorkspaceTokenDeploymentRole("token-id", "", "", deploymentID, out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -958,7 +958,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = RemoveWorkspaceTokenDeploymentRole("token-id", "", "", "", out, mockClient, mockIamClient) + err = RemoveWorkspaceTokenDeploymentRole("token-id", "", "", deploymentID, out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) } @@ -984,7 +984,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertOrgTokenDeploymentRole("", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertOrgTokenDeploymentRole("", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -1005,7 +1005,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertOrgTokenDeploymentRole("", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertOrgTokenDeploymentRole("", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -1028,7 +1028,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertOrgTokenDeploymentRole("", "", "", "", "update", out, mockClient, mockIamClient) + err = UpsertOrgTokenDeploymentRole("", "", "", deploymentID, "update", out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -1049,7 +1049,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertOrgTokenDeploymentRole("", "", "", "", "update", out, mockClient, mockIamClient) + err = UpsertOrgTokenDeploymentRole("", "", "", deploymentID, "update", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -1070,7 +1070,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertOrgTokenDeploymentRole("", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertOrgTokenDeploymentRole("", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) @@ -1092,7 +1092,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertOrgTokenDeploymentRole("", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertOrgTokenDeploymentRole("", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to update token") }) @@ -1114,7 +1114,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertOrgTokenDeploymentRole("token-id", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertOrgTokenDeploymentRole("token-id", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -1135,7 +1135,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertOrgTokenDeploymentRole("token-id", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertOrgTokenDeploymentRole("token-id", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) } @@ -1161,7 +1161,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -1182,7 +1182,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -1205,7 +1205,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "update", out, mockClient, mockIamClient) + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", deploymentID, "update", out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -1226,7 +1226,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "update", out, mockClient, mockIamClient) + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", deploymentID, "update", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to list tokens") }) @@ -1247,7 +1247,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) @@ -1269,7 +1269,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertWorkspaceTokenDeploymentRole("", "", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to update token") }) @@ -1291,7 +1291,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertWorkspaceTokenDeploymentRole("token-id", "", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertWorkspaceTokenDeploymentRole("token-id", "", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.NoError(t, err) assert.Equal(t, expectedOutMessage, out.String()) }) @@ -1312,7 +1312,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { // Restore stdin right after the test. defer func() { os.Stdin = stdin }() os.Stdin = r - err = UpsertWorkspaceTokenDeploymentRole("token-id", "", "", "", "", "create", out, mockClient, mockIamClient) + err = UpsertWorkspaceTokenDeploymentRole("token-id", "", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) } From f8fd97d7a4736ce9d0a936703cc984dd474c7b49 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 09:39:47 -0400 Subject: [PATCH 20/26] modify action from create to add --- cmd/cloud/deployment.go | 32 ++++++++++++++++---------------- cmd/cloud/deployment_test.go | 12 ++++++------ cmd/cloud/workspace.go | 16 ++++++++-------- cmd/cloud/workspace_test.go | 6 +++--- 4 files changed, 33 insertions(+), 33 deletions(-) diff --git a/cmd/cloud/deployment.go b/cmd/cloud/deployment.go index f3496d94a..ff943034d 100644 --- a/cmd/cloud/deployment.go +++ b/cmd/cloud/deployment.go @@ -1040,7 +1040,7 @@ func newOrgTokenManageCmd(out io.Writer) *cobra.Command { } cmd.SetOut(out) cmd.AddCommand( - newCreateOrganizationTokenDeploymentRole(out), + newAddOrganizationTokenDeploymentRole(out), newUpdateOrganizationTokenDeploymentRole(out), newRemoveOrganizationTokenDeploymentRole(out), newListOrganizationTokensInDeployment(out), @@ -1057,7 +1057,7 @@ func newWorkspaceTokenManageCmd(out io.Writer) *cobra.Command { } cmd.SetOut(out) cmd.AddCommand( - newCreateWorkspaceTokenDeploymentRole(out), + newAddWorkspaceTokenDeploymentRole(out), newUpdateWorkspaceTokenDeploymentRole(out), newRemoveWorkspaceTokenDeploymentRole(out), newListWorkspaceTokensInDeployment(out), @@ -1065,13 +1065,13 @@ func newWorkspaceTokenManageCmd(out io.Writer) *cobra.Command { return cmd } -func newCreateOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { +func newAddOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "create [ORG_TOKEN_ID]", - Short: "Create an Organization API token's Deployment Role", - Long: "Create an Organization API token's Deployment Role\n$astro deployment token organization-token create [ORG_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + Use: "add [ORG_TOKEN_ID]", + Short: "Add an Organization API token to a Deployment", + Long: "Add an Organization API token to a Deployment\n$astro deployment token organization-token add [ORG_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", RunE: func(cmd *cobra.Command, args []string) error { - return createOrgTokenToDeploymentRole(cmd, args, out) + return addOrgTokenToDeploymentRole(cmd, args, out) }, } cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") @@ -1095,13 +1095,13 @@ func newUpdateOrganizationTokenDeploymentRole(out io.Writer) *cobra.Command { return cmd } -func newCreateWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { +func newAddWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "create [WORKSPACE_TOKEN_ID]", - Short: "Create a Workspace API token's Deployment Role", - Long: "Create a Workspace API token's Deployment Role\n$astro deployment token workspace-token create [WORKSPACE_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", + Use: "add [WORKSPACE_TOKEN_ID]", + Short: "Add a Workspace API token's Deployment Role", + Long: "Add a Workspace API token's Deployment Role\n$astro deployment token workspace-token add [WORKSPACE_TOKEN_ID] --name [token name] --role [DEPLOYMENT_ADMIN or a custom role name].", RunE: func(cmd *cobra.Command, args []string) error { - return createWorkspaceTokenDeploymentRole(cmd, args, out) + return addWorkspaceTokenDeploymentRole(cmd, args, out) }, } cmd.Flags().StringVarP(&orgTokenName, "workspace-token-name", "n", "", "The name of the WORKSPACE API token you want to add to a Deployment. If the name contains a space, specify the entire name within quotes \"\" ") @@ -1125,7 +1125,7 @@ func newUpdateWorkspaceTokenDeploymentRole(out io.Writer) *cobra.Command { return cmd } -func createOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { +func addOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } @@ -1136,7 +1136,7 @@ func createOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Wr } if tokenRole == "" { // no role was provided so ask the user for it - tokenRole = input.Text("Enter a role for the new Deployment API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") + tokenRole = input.Text("Enter a role for the API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") } cmd.SilenceUsage = true @@ -1161,7 +1161,7 @@ func updateOrgTokenToDeploymentRole(cmd *cobra.Command, args []string, out io.Wr return deployment.UpsertOrgTokenDeploymentRole(orgTokenID, orgTokenName, tokenRole, deploymentID, "update", out, astroCoreClient, astroCoreIamClient) } -func createWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { +func addWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out io.Writer) error { if deploymentID == "" { return errors.New("flag --deployment-id is required") } @@ -1173,7 +1173,7 @@ func createWorkspaceTokenDeploymentRole(cmd *cobra.Command, args []string, out i if tokenRole == "" { // no role was provided so ask the user for it - tokenRole = input.Text("Enter a role for the new Deployment API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") + tokenRole = input.Text("Enter a role for the API token (Possible values are DEPLOYMENT_ADMIN or a custom role name): ") } cmd.SilenceUsage = true diff --git a/cmd/cloud/deployment_test.go b/cmd/cloud/deployment_test.go index 8abd729e5..b8710f747 100644 --- a/cmd/cloud/deployment_test.go +++ b/cmd/cloud/deployment_test.go @@ -2423,7 +2423,7 @@ func TestDeploymentTokenDelete(t *testing.T) { }) } -func TestCreateWorkspaceTokenDeploymentRole(t *testing.T) { +func TestAddWorkspaceTokenDeploymentRole(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) t.Run("happy path Create", func(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) @@ -2436,7 +2436,7 @@ func TestCreateWorkspaceTokenDeploymentRole(t *testing.T) { astroCoreClient = mockClient astroCoreIamClient = mockIamClient - cmdArgs := []string{"token", "workspace-token", "create", "--deployment-id", mockDeploymentID, "--role", "DEPLOYMENT_ADMIN"} + cmdArgs := []string{"token", "workspace-token", "add", "--deployment-id", mockDeploymentID, "--role", "DEPLOYMENT_ADMIN"} _, err := execDeploymentCmd(cmdArgs...) assert.NoError(t, err) }) @@ -2450,7 +2450,7 @@ func TestCreateWorkspaceTokenDeploymentRole(t *testing.T) { defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient astroCoreIamClient = mockIamClient - cmdArgs := []string{"token", "workspace-token", "create", "token-id", "--deployment-id", mockDeploymentID} + cmdArgs := []string{"token", "workspace-token", "add", "token-id", "--deployment-id", mockDeploymentID} _, err := execDeploymentCmd(cmdArgs...) assert.NoError(t, err) }) @@ -2489,7 +2489,7 @@ func TestUpdateWorkspaceTokenDeploymentRole(t *testing.T) { }) } -func TestCreateOrganizationTokenDeploymentRole(t *testing.T) { +func TestAddOrganizationTokenDeploymentRole(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) t.Run("happy path Create", func(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) @@ -2502,7 +2502,7 @@ func TestCreateOrganizationTokenDeploymentRole(t *testing.T) { astroCoreClient = mockClient astroCoreIamClient = mockIamClient - cmdArgs := []string{"token", "organization-token", "create", "--deployment-id", mockDeploymentID, "--role", "DEPLOYMENT_ADMIN"} + cmdArgs := []string{"token", "organization-token", "add", "--deployment-id", mockDeploymentID, "--role", "DEPLOYMENT_ADMIN"} _, err := execDeploymentCmd(cmdArgs...) assert.NoError(t, err) }) @@ -2516,7 +2516,7 @@ func TestCreateOrganizationTokenDeploymentRole(t *testing.T) { defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient astroCoreIamClient = mockIamClient - cmdArgs := []string{"token", "organization-token", "create", "token-id", "--deployment-id", mockDeploymentID} + cmdArgs := []string{"token", "organization-token", "add", "token-id", "--deployment-id", mockDeploymentID} _, err := execDeploymentCmd(cmdArgs...) assert.NoError(t, err) }) diff --git a/cmd/cloud/workspace.go b/cmd/cloud/workspace.go index e6b359443..3dfa66f48 100644 --- a/cmd/cloud/workspace.go +++ b/cmd/cloud/workspace.go @@ -385,7 +385,7 @@ func newWorkspaceOrgTokenManageCmd(out io.Writer) *cobra.Command { } cmd.SetOut(out) cmd.AddCommand( - newCreateOrganizationTokenWorkspaceRole(out), + newAddOrganizationTokenWorkspaceRole(out), newUpdateOrganizationTokenWorkspaceRole(out), newRemoveOrganizationTokenWorkspaceRole(out), newListOrganizationTokensInWorkspace(out), @@ -393,13 +393,13 @@ func newWorkspaceOrgTokenManageCmd(out io.Writer) *cobra.Command { return cmd } -func newCreateOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { +func newAddOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { cmd := &cobra.Command{ - Use: "create [ORG_TOKEN_ID]", - Short: "Create an Organization API token's Workspace Role", - Long: "Create an Organization API token's Workspace Role\n$astro workspace token organization-token create [ORG_TOKEN_ID] --name [token name] --role [" + allowedWorkspaceRoleNames + "].", + Use: "add [ORG_TOKEN_ID]", + Short: "Add an Organization API token to a Workspace", + Long: "Add an Organization API token to a Workspace\n$astro workspace token organization-token add [ORG_TOKEN_ID] --name [token name] --role [" + allowedWorkspaceRoleNames + "].", RunE: func(cmd *cobra.Command, args []string) error { - return createOrgTokenWorkspaceRole(cmd, args, out) + return addOrgTokenWorkspaceRole(cmd, args, out) }, } cmd.Flags().StringVarP(&orgTokenName, "org-token-name", "n", "", "The name of the Organization API token you want to add to a Workspace. If the name contains a space, specify the entire name within quotes \"\" ") @@ -423,7 +423,7 @@ func newUpdateOrganizationTokenWorkspaceRole(out io.Writer) *cobra.Command { return cmd } -func createOrgTokenWorkspaceRole(cmd *cobra.Command, args []string, out io.Writer) error { +func addOrgTokenWorkspaceRole(cmd *cobra.Command, args []string, out io.Writer) error { // if an id was provided in the args we use it if len(args) > 0 { // make sure the id is lowercase @@ -431,7 +431,7 @@ func createOrgTokenWorkspaceRole(cmd *cobra.Command, args []string, out io.Write } if tokenRole == "" { // no role was provided so ask the user for it - tokenRole = input.Text("Enter a role for the new Workspace API token. Possible values are " + allowedWorkspaceRoleNamesProse + ": ") + tokenRole = input.Text("Enter a role for the API token. Possible values are " + allowedWorkspaceRoleNamesProse + ": ") } cmd.SilenceUsage = true diff --git a/cmd/cloud/workspace_test.go b/cmd/cloud/workspace_test.go index 5689a0635..7bf91d09f 100644 --- a/cmd/cloud/workspace_test.go +++ b/cmd/cloud/workspace_test.go @@ -1629,7 +1629,7 @@ func TestWorkspaceTokenAdd(t *testing.T) { }) } -func TestCreateOrganizationTokenWorkspaceRole(t *testing.T) { +func TestAddOrganizationTokenWorkspaceRole(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) t.Run("happy path Create", func(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) @@ -1642,7 +1642,7 @@ func TestCreateOrganizationTokenWorkspaceRole(t *testing.T) { astroCoreClient = mockClient astroCoreIamClient = mockIamClient - cmdArgs := []string{"token", "organization-token", "create", "--role", "DEPLOYMENT_ADMIN"} + cmdArgs := []string{"token", "organization-token", "add", "--role", "DEPLOYMENT_ADMIN"} _, err := execWorkspaceCmd(cmdArgs...) assert.NoError(t, err) }) @@ -1656,7 +1656,7 @@ func TestCreateOrganizationTokenWorkspaceRole(t *testing.T) { defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient astroCoreIamClient = mockIamClient - cmdArgs := []string{"token", "organization-token", "create", "token-id"} + cmdArgs := []string{"token", "organization-token", "add", "token-id"} _, err := execWorkspaceCmd(cmdArgs...) assert.NoError(t, err) }) From a31b390c7905476435ca3f2e73e3d557dac3572b Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 11:13:39 -0400 Subject: [PATCH 21/26] add checks to prevent modification of wrong token types from commands --- cloud/deployment/deployment_token.go | 28 +++++-- cloud/deployment/deployment_token_test.go | 82 +++++++++++-------- cloud/organization/organization_token.go | 4 + cloud/workspace-token/workspace_token.go | 22 ++++- cloud/workspace-token/workspace_token_test.go | 70 +++++++++------- cmd/cloud/deployment_test.go | 26 +++--- cmd/cloud/organization_test.go | 4 +- cmd/cloud/workspace_test.go | 41 +++++++--- 8 files changed, 177 insertions(+), 100 deletions(-) diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index ff43be1e9..0bbc1d2b8 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -4,6 +4,7 @@ import ( httpContext "context" "errors" "fmt" + "golang.org/x/exp/slices" "io" "os" "strconv" @@ -38,11 +39,13 @@ var ( ErrDeploymentTokenNotFound = errors.New("no Deployment API token was found for the API token name you provided") errWorkspaceTokenInDeployment = errors.New("this Workspace API token has already been added to the Deployment with that role") errOrgTokenInDeployment = errors.New("this Organization API token has already been added to the Deployment with that role") + errWrongTokenTypeSelected = errors.New("the token selected is not of the type you are trying to modify") ) const ( - deploymentEntity = "DEPLOYMENT" - workspaceEntity = "WORKSPACE" + deploymentEntity = "DEPLOYMENT" + workspaceEntity = "WORKSPACE" + organizationEntity = "ORGANIZATION" ) // List all deployment Tokens @@ -418,6 +421,19 @@ func GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID stri return token, err } } + + if tokenTypes != nil { // verify the user has passed in an id that matches the operations expected token type + if len(*tokenTypes) > 0 { + stringTokenTypes := []string{} + for _, tokenType := range *tokenTypes { + stringTokenTypes = append(stringTokenTypes, string(tokenType)) + } + if !slices.Contains(stringTokenTypes, string(token.Type)) { + return token, errWrongTokenTypeSelected + } + } + } + return token, err } @@ -445,7 +461,7 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl continue // this removes the role in question } - if roles[i].EntityId == ctx.Organization { + if roles[i].EntityType == organizationEntity { orgRole = roles[i].Role } @@ -515,7 +531,7 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace, deployment string, continue // this removes the role in question } - if roles[i].EntityId == ctx.Workspace { + if roles[i].EntityType == workspaceEntity { workspaceRole = roles[i].Role } @@ -593,7 +609,7 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o } } - if roles[i].EntityId == ctx.Workspace { + if roles[i].EntityType == workspaceEntity { workspaceRole = roles[i].Role } @@ -663,7 +679,7 @@ func UpsertOrgTokenDeploymentRole(id, name, role, deployment, operation string, } } - if roles[i].EntityId == ctx.Organization { + if roles[i].EntityType == organizationEntity { orgRole = roles[i].Role } diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 96e8c3096..6bb3dcc6f 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -26,13 +26,31 @@ var ( fullName2 = "User 2" token = "token" - iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: deploymentID, Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} - GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ + iamAPIOrgnaizationToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + GetAPITokensResponseOKOrganizationToken = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &iamAPIToken, + JSON200: &iamAPIOrgnaizationToken, } + iamAPIWorkspaceToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + + GetAPITokensResponseOKWorkspaceToken = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &iamAPIWorkspaceToken, + } + + iamAPIDeploymentToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + + GetAPITokensResponseOKDeploymentToken = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &iamAPIDeploymentToken, + } + errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", }) @@ -299,7 +317,7 @@ func TestUpdateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) @@ -309,7 +327,7 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Twice() @@ -333,7 +351,7 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponse2O0, nil).Twice() @@ -357,7 +375,7 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseOK, nil) @@ -399,7 +417,7 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseError, nil) err := UpdateToken("token3", "", "", "", "", "", out, mockClient, mockIamClient) @@ -419,7 +437,7 @@ func TestUpdateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) @@ -434,7 +452,7 @@ func TestRotateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("RotateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateDeploymentAPITokenResponseOK, nil) @@ -446,7 +464,7 @@ func TestRotateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) @@ -459,7 +477,7 @@ func TestRotateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) @@ -472,7 +490,7 @@ func TestRotateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) @@ -524,7 +542,7 @@ func TestRotateToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) @@ -539,7 +557,7 @@ func TestDeleteToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Twice() @@ -552,7 +570,7 @@ func TestDeleteToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("DeleteDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteDeploymentAPITokenResponseOK, nil) @@ -564,7 +582,7 @@ func TestDeleteToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("DeleteDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteDeploymentAPITokenResponseOK, nil) @@ -626,7 +644,7 @@ func TestDeleteToken(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) out := new(bytes.Buffer) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil) @@ -706,7 +724,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -770,7 +788,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -792,7 +810,7 @@ func TestRemoveOrgTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -839,7 +857,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -903,7 +921,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseError, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -925,7 +943,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -972,7 +990,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -1016,7 +1034,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -1080,7 +1098,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -1102,7 +1120,7 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -1149,7 +1167,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -1193,7 +1211,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -1257,7 +1275,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseError, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -1279,7 +1297,7 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index 586c785b2..9743dbeba 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -23,6 +23,7 @@ var ( errInvalidOrganizationTokenKey = errors.New("invalid Organization API token selection") errOrganizationTokenNotFound = errors.New("organization token specified was not found") errOrgTokenInWorkspace = errors.New("this Organization API token has already been added to the Workspace with that role") + errWrongTokenTypeSelected = errors.New("the token selected is not of the type you are trying to modify") ) const ( @@ -295,6 +296,9 @@ func GetTokenFromInputOrUser(id, name, organization string, client astrocore.Cor return token, err } } + if token.Type != organizationEntity { + return token, errWrongTokenTypeSelected + } return token, err } diff --git a/cloud/workspace-token/workspace_token.go b/cloud/workspace-token/workspace_token.go index 7eab7c09e..8a2462b1e 100644 --- a/cloud/workspace-token/workspace_token.go +++ b/cloud/workspace-token/workspace_token.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "os" + "slices" "strconv" "time" @@ -39,11 +40,13 @@ var ( errWorkspaceTokenInDeployment = errors.New("this Workspace API token has already been added to the Deployment with that role") ErrWorkspaceTokenNotFound = errors.New("no Workspace API token was found for the API token name you provided") errOrgTokenInWorkspace = errors.New("this Organization API token has already been added to the Workspace with that role") + errWrongTokenTypeSelected = errors.New("the token selected is not of the type you are trying to modify") ) const ( - workspaceEntity = "WORKSPACE" - deploymentEntity = "DEPLOYMENT" + workspaceEntity = "WORKSPACE" + deploymentEntity = "DEPLOYMENT" + organizationEntity = "ORGANIZATION" ) // List all workspace Tokens @@ -483,6 +486,17 @@ func GetTokenFromInputOrUser(id, name, workspace, organizationID string, tokenTy return token, err } } + if tokenTypes != nil { // verify the user has passed in an id that matches the operations expected token type + if len(*tokenTypes) > 0 { + stringTokenTypes := []string{} + for _, tokenType := range *tokenTypes { + stringTokenTypes = append(stringTokenTypes, string(tokenType)) + } + if !slices.Contains(stringTokenTypes, string(token.Type)) { + return token, errWrongTokenTypeSelected + } + } + } return token, err } @@ -515,7 +529,7 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie continue // this removes the role in question } - if roles[i].EntityId == organizationID { + if roles[i].EntityType == organizationEntity { orgRole = roles[i].Role } @@ -598,7 +612,7 @@ func UpsertOrgTokenWorkspaceRole(id, name, role, workspace, operation string, ou } } - if roles[i].EntityId == ctx.Organization { + if roles[i].EntityType == organizationEntity { orgRole = roles[i].Role } diff --git a/cloud/workspace-token/workspace_token_test.go b/cloud/workspace-token/workspace_token_test.go index 61d635581..864588c77 100644 --- a/cloud/workspace-token/workspace_token_test.go +++ b/cloud/workspace-token/workspace_token_test.go @@ -20,18 +20,26 @@ import ( ) var ( - workspaceID = "ck05r3bor07h40d02y2hw4n4v" - description1 = "Description 1" - description2 = "Description 2" - fullName1 = "User 1" - fullName2 = "User 2" - token = "token" - iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} - GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ + workspaceID = "ck05r3bor07h40d02y2hw4n4v" + description1 = "Description 1" + description2 = "Description 2" + fullName1 = "User 1" + fullName2 = "User 2" + token = "token" + iamAPIOrgnaizationToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + GetAPITokensResponseOKOrganizationToken = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &iamAPIToken, + JSON200: &iamAPIOrgnaizationToken, + } + iamAPIWorkspaceToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + + GetAPITokensResponseOKWorkspaceToken = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &iamAPIWorkspaceToken, } errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", @@ -283,7 +291,7 @@ func TestUpdateToken(t *testing.T) { mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -296,7 +304,7 @@ func TestUpdateToken(t *testing.T) { mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -320,7 +328,7 @@ func TestUpdateToken(t *testing.T) { mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -343,7 +351,7 @@ func TestUpdateToken(t *testing.T) { mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) @@ -384,7 +392,7 @@ func TestUpdateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseError, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := UpdateToken("token3", "", "", "", "", "", out, mockClient, mockIamClient) assert.Equal(t, "failed to update workspace token", err.Error()) @@ -405,7 +413,7 @@ func TestUpdateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := UpdateToken("token1", "", "", "", "Invalid Role", "", out, mockClient, mockIamClient) assert.Equal(t, user.ErrInvalidWorkspaceRole.Error(), err.Error()) @@ -417,7 +425,7 @@ func TestUpdateToken(t *testing.T) { mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := UpdateToken("", apiToken1.Name, "", "", "WORKSPACE_MEMBER", "", out, mockClient, mockIamClient) assert.NoError(t, err) @@ -431,7 +439,7 @@ func TestRotateToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("RotateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := RotateToken("token1", "", "", false, true, out, mockClient, mockIamClient) assert.NoError(t, err) @@ -444,7 +452,7 @@ func TestRotateToken(t *testing.T) { mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("RotateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient, mockIamClient) assert.NoError(t, err) @@ -457,7 +465,7 @@ func TestRotateToken(t *testing.T) { mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("RotateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := RotateToken("", apiToken1.Name, "", true, false, out, mockClient, mockIamClient) assert.NoError(t, err) @@ -509,7 +517,7 @@ func TestRotateToken(t *testing.T) { mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("RotateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateWorkspaceAPITokenResponseError, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := RotateToken("", apiToken1.Name, "", false, true, out, mockClient, mockIamClient) assert.Equal(t, "failed to update workspace token", err.Error()) @@ -524,7 +532,7 @@ func TestDeleteToken(t *testing.T) { mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Twice() mockClient.On("DeleteWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := DeleteToken("", apiToken1.Name, "", false, out, mockClient, mockIamClient) assert.NoError(t, err) @@ -536,7 +544,7 @@ func TestDeleteToken(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("DeleteWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := DeleteToken("token1", "", "", false, out, mockClient, mockIamClient) assert.NoError(t, err) @@ -549,7 +557,7 @@ func TestDeleteToken(t *testing.T) { mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Twice() mockClient.On("DeleteWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteWorkspaceAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := DeleteToken("", apiToken1.Name, "", false, out, mockClient, mockIamClient) assert.NoError(t, err) @@ -602,7 +610,7 @@ func TestDeleteToken(t *testing.T) { mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) mockClient.On("DeleteWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteWorkspaceAPITokenResponseError, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) err := DeleteToken("", apiToken1.Name, "", true, out, mockClient, mockIamClient) assert.Equal(t, "failed to update workspace token", err.Error()) @@ -679,7 +687,7 @@ func TestUpsertOrgTokenWorkspaceRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -723,7 +731,7 @@ func TestUpsertOrgTokenWorkspaceRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -787,7 +795,7 @@ func TestUpsertOrgTokenWorkspaceRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -809,7 +817,7 @@ func TestUpsertOrgTokenWorkspaceRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -856,7 +864,7 @@ func TestRemoveOrgTokenWorkspaceRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -920,7 +928,7 @@ func TestRemoveOrgTokenWorkspaceRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() @@ -942,7 +950,7 @@ func TestRemoveOrgTokenWorkspaceRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin expectedInput := []byte("2") r, w, err := os.Pipe() diff --git a/cmd/cloud/deployment_test.go b/cmd/cloud/deployment_test.go index b8710f747..66a3d0261 100644 --- a/cmd/cloud/deployment_test.go +++ b/cmd/cloud/deployment_test.go @@ -2152,7 +2152,7 @@ func TestDeploymentTokenUpdate(t *testing.T) { astroCoreClient = mockClient mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKDeploymentToken, nil) astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "update", "--name", tokenName1, "--deployment-id", mockDeploymentID} @@ -2430,7 +2430,7 @@ func TestAddWorkspaceTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient @@ -2445,7 +2445,7 @@ func TestAddWorkspaceTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient @@ -2464,7 +2464,7 @@ func TestUpdateWorkspaceTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient @@ -2478,7 +2478,7 @@ func TestUpdateWorkspaceTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() // mock os.Stdin defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient @@ -2496,7 +2496,7 @@ func TestAddOrganizationTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient @@ -2511,7 +2511,7 @@ func TestAddOrganizationTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient @@ -2530,7 +2530,7 @@ func TestUpdateOrganizationTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient @@ -2544,7 +2544,7 @@ func TestUpdateOrganizationTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient @@ -2562,7 +2562,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient astroCoreIamClient = mockIamClient @@ -2575,7 +2575,7 @@ func TestRemoveWorkspaceTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() astroCoreClient = mockClient astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "workspace-token", "remove", "token-id", "--deployment-id", mockDeploymentID} @@ -2591,7 +2591,7 @@ func TestRemoveOrganizationTokenDeploymentRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListDeploymentApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListDeploymentAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient astroCoreIamClient = mockIamClient @@ -2604,7 +2604,7 @@ func TestRemoveOrganizationTokenDeploymentRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() astroCoreClient = mockClient astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "organization-token", "remove", "token-id", "--deployment-id", mockDeploymentID} diff --git a/cmd/cloud/organization_test.go b/cmd/cloud/organization_test.go index 1caeef852..f1b939644 100644 --- a/cmd/cloud/organization_test.go +++ b/cmd/cloud/organization_test.go @@ -1250,7 +1250,7 @@ func TestOrganizationTokenUpdate(t *testing.T) { astroCoreClient = mockClient mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil) astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "update", "--name", tokenName1} @@ -1513,7 +1513,7 @@ func TestOrganizationTokenListRoles(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil) astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "roles", mockTokenID} _, err := execOrganizationCmd(cmdArgs...) diff --git a/cmd/cloud/workspace_test.go b/cmd/cloud/workspace_test.go index 7bf91d09f..dfa6405a8 100644 --- a/cmd/cloud/workspace_test.go +++ b/cmd/cloud/workspace_test.go @@ -1031,12 +1031,29 @@ var ( apiToken1, {Id: "token2", Name: "Token 2", Description: description2, Type: "Type 2", Roles: []astrocore.ApiTokenRole{{EntityId: mockWorkspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_MEMBER"}}, CreatedAt: time.Now(), CreatedBy: &astrocore.BasicSubjectProfile{FullName: &fullName2}}, } - iamAPIToken = astroiamcore.ApiToken{Id: "token1", Name: tokenName1, Token: &token, Description: description1, Type: "Type 1", Roles: &[]astroiamcore.ApiTokenRole{{EntityId: mockWorkspaceID, EntityType: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} - GetAPITokensResponseOK = astroiamcore.GetApiTokenResponse{ + iamAPIOrgnaizationToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: mockWorkspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + GetAPITokensResponseOKOrganizationToken = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, - JSON200: &iamAPIToken, + JSON200: &iamAPIOrgnaizationToken, + } + iamAPIWorkspaceToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: mockWorkspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + + GetAPITokensResponseOKWorkspaceToken = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &iamAPIWorkspaceToken, + } + + iamAPIDeploymentToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "DEPLOYMENT", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + + GetAPITokensResponseOKDeploymentToken = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &iamAPIDeploymentToken, } errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", @@ -1274,7 +1291,7 @@ func TestWorkspaceTokenUpdate(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseError, nil) astroCoreClient = mockClient astroCoreIamClient = mockIamClient @@ -1574,7 +1591,7 @@ func TestWorkspaceTokenAdd(t *testing.T) { mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) astroCoreClient = mockClient mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil) astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "add", "--org-token-name", tokenName2, "--role", "WORKSPACE_MEMBER"} @@ -1608,7 +1625,7 @@ func TestWorkspaceTokenAdd(t *testing.T) { mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil) astroCoreIamClient = mockIamClient // mock os.Stdin @@ -1636,7 +1653,7 @@ func TestAddOrganizationTokenWorkspaceRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient @@ -1651,7 +1668,7 @@ func TestAddOrganizationTokenWorkspaceRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient @@ -1670,7 +1687,7 @@ func TestUpdateOrganizationTokenWorkspaceRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient @@ -1684,7 +1701,7 @@ func TestUpdateOrganizationTokenWorkspaceRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() // mock os.Stdin defer testUtil.MockUserInput(t, "DEPLOYMENT_ADMIN")() astroCoreClient = mockClient @@ -1702,7 +1719,7 @@ func TestRemoveOrganizationTokenWorkspaceRole(t *testing.T) { mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListWorkspaceApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListWorkspaceAPITokensResponseOK, nil).Once() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() defer testUtil.MockUserInput(t, "1")() astroCoreClient = mockClient astroCoreIamClient = mockIamClient @@ -1715,7 +1732,7 @@ func TestRemoveOrganizationTokenWorkspaceRole(t *testing.T) { mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() - mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() astroCoreClient = mockClient astroCoreIamClient = mockIamClient cmdArgs := []string{"token", "organization-token", "remove", "token-id"} From 1e236626831b004942f98c5d23a650a17a33d521 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 11:22:27 -0400 Subject: [PATCH 22/26] add test coverage --- cloud/deployment/deployment_token_test.go | 54 +++++++++++++++++++ cloud/workspace-token/workspace_token_test.go | 21 ++++++++ cmd/cloud/organization_test.go | 3 +- 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 6bb3dcc6f..857b29cee 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -445,6 +445,18 @@ func TestUpdateToken(t *testing.T) { err := UpdateToken("", apiToken1.Name, "", "", "DEPLOYMENT_MEMBER", "", out, mockClient, mockIamClient) assert.NoError(t, err) }) + + t.Run("error path wrong token type provided", func(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + out := new(bytes.Buffer) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateDeploymentApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateDeploymentAPITokenResponseOK, nil) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil) + + err := UpdateToken("token1", "", "", "", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "the token selected is not of the type you are trying to modify") + }) } func TestRotateToken(t *testing.T) { @@ -1156,6 +1168,27 @@ func TestUpsertOrgTokenDeploymentRole(t *testing.T) { err = UpsertOrgTokenDeploymentRole("token-id", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) + + t.Run("error path with token id passed in - wrong token type", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenDeploymentRole("token-id", "", "", deploymentID, "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "the token selected is not of the type you are trying to modify") + }) } func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { @@ -1333,4 +1366,25 @@ func TestUpsertWorkspaceTokenDeploymentRole(t *testing.T) { err = UpsertWorkspaceTokenDeploymentRole("token-id", "", "", "", deploymentID, "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) + + t.Run("error path with token id passed in - wrong token type", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateWorkspaceApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateWorkspaceAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKOrganizationToken, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertWorkspaceTokenDeploymentRole("token-id", "", "", "", deploymentID, "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "the token selected is not of the type you are trying to modify") + }) } diff --git a/cloud/workspace-token/workspace_token_test.go b/cloud/workspace-token/workspace_token_test.go index 864588c77..8eab27d76 100644 --- a/cloud/workspace-token/workspace_token_test.go +++ b/cloud/workspace-token/workspace_token_test.go @@ -853,6 +853,27 @@ func TestUpsertOrgTokenWorkspaceRole(t *testing.T) { err = UpsertOrgTokenWorkspaceRole("token-id", "", "", "", "create", out, mockClient, mockIamClient) assert.ErrorContains(t, err, "failed to get token") }) + + t.Run("error path with token id passed in - wrong token type", func(t *testing.T) { + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil).Once() + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil).Once() + // mock os.Stdin + expectedInput := []byte("2") + r, w, err := os.Pipe() + assert.NoError(t, err) + _, err = w.Write(expectedInput) + assert.NoError(t, err) + w.Close() + stdin := os.Stdin + // Restore stdin right after the test. + defer func() { os.Stdin = stdin }() + os.Stdin = r + err = UpsertOrgTokenWorkspaceRole("token-id", "", "", "", "create", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "the token selected is not of the type you are trying to modify") + }) } func TestRemoveOrgTokenWorkspaceRole(t *testing.T) { diff --git a/cmd/cloud/organization_test.go b/cmd/cloud/organization_test.go index f1b939644..3adf72ab9 100644 --- a/cmd/cloud/organization_test.go +++ b/cmd/cloud/organization_test.go @@ -1267,7 +1267,7 @@ func TestOrganizationTokenUpdate(t *testing.T) { assert.Error(t, err) mockClient.AssertExpectations(t) }) - t.Run("token is updated", func(t *testing.T) { + t.Run("token is updated -- name provided", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) mockClient.On("ListOrganizationApiTokensWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&ListOrganizationAPITokensResponseOK, nil) @@ -1278,6 +1278,7 @@ func TestOrganizationTokenUpdate(t *testing.T) { assert.NoError(t, err) mockClient.AssertExpectations(t) }) + t.Run("token is created with no ID provided", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) From 3ff6018aa7f6dea72e36010ecc5c71fdf200c07b Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 11:28:30 -0400 Subject: [PATCH 23/26] increase test coverage --- cloud/organization/organization_token_test.go | 43 +++++++++++++++---- cmd/cloud/organization_test.go | 1 - 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/cloud/organization/organization_token_test.go b/cloud/organization/organization_token_test.go index 359ce3329..9cfed4c26 100644 --- a/cloud/organization/organization_token_test.go +++ b/cloud/organization/organization_token_test.go @@ -35,6 +35,16 @@ var ( errorTokenGet, _ = json.Marshal(astroiamcore.Error{ Message: "failed to get token", }) + + iamAPIWorkspaceToken = astroiamcore.ApiToken{Id: "token1", Name: "token1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + + GetAPITokensResponseOKWorkspaceToken = astroiamcore.GetApiTokenResponse{ + HTTPResponse: &http.Response{ + StatusCode: 200, + }, + JSON200: &iamAPIWorkspaceToken, + } + GetAPITokensResponseError = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 500, @@ -232,13 +242,25 @@ func TestAddOrgTokenToWorkspace(t *testing.T) { mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) err := AddOrgTokenToWorkspace(selectedTokenID, "", role, workspace, out, mockClient, mockIamClient) assert.NoError(t, err) }) + t.Run("error add organization token to workspace using id - wrong token type", func(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) + + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) + + err := AddOrgTokenToWorkspace(selectedTokenID, "", role, workspace, out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "the token selected is not of the type you are trying to modify") + }) + t.Run("return error for failed to get organization token", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) @@ -394,7 +416,6 @@ func TestUpdateToken(t *testing.T) { mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil).Twice() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) err := UpdateToken("token1", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) @@ -455,7 +476,6 @@ func TestUpdateToken(t *testing.T) { mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil).Twice() mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) err := UpdateToken("token1", "", "", "", "", out, mockClient, mockIamClient) assert.NoError(t, err) @@ -499,7 +519,6 @@ func TestUpdateToken(t *testing.T) { mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseError, nil) err := UpdateToken("token3", "", "", "", "", out, mockClient, mockIamClient) assert.Equal(t, "failed to update token", err.Error()) @@ -521,7 +540,6 @@ func TestUpdateToken(t *testing.T) { mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) err := UpdateToken("token1", "", "", "", "Invalid Role", out, mockClient, mockIamClient) assert.Equal(t, user.ErrInvalidOrganizationRole.Error(), err.Error()) @@ -546,11 +564,22 @@ func TestUpdateToken(t *testing.T) { mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) err := UpdateToken("token1", "", "", "", "ORGANIZATION_MEMBER", out, mockClient, mockIamClient) assert.NoError(t, err) }) + + t.Run("error path - wrong token type", func(t *testing.T) { + testUtil.InitTestConfig(testUtil.LocalPlatform) + out := new(bytes.Buffer) + mockIamClient := new(astroiamcore_mocks.ClientWithResponsesInterface) + mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOKWorkspaceToken, nil) + + mockClient := new(astrocore_mocks.ClientWithResponsesInterface) + mockClient.On("UpdateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&UpdateOrganizationAPITokenResponseOK, nil) + err := UpdateToken("token1", "", "", "", "", out, mockClient, mockIamClient) + assert.ErrorContains(t, err, "the token selected is not of the type you are trying to modify") + }) } func TestRotateToken(t *testing.T) { @@ -561,7 +590,6 @@ func TestRotateToken(t *testing.T) { mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil) mockClient.On("RotateOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&RotateOrganizationAPITokenResponseOK, nil) err := RotateToken("token1", "", false, true, out, mockClient, mockIamClient) assert.NoError(t, err) @@ -667,7 +695,6 @@ func TestDeleteToken(t *testing.T) { mockIamClient.On("GetApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything).Return(&GetAPITokensResponseOK, nil) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) - mockClient.On("GetOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&GetOrganizationAPITokenResponseOK, nil).Twice() mockClient.On("DeleteOrganizationApiTokenWithResponse", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&DeleteOrganizationAPITokenResponseOK, nil) err := DeleteToken("token1", "", false, out, mockClient, mockIamClient) assert.NoError(t, err) diff --git a/cmd/cloud/organization_test.go b/cmd/cloud/organization_test.go index 3adf72ab9..cc3b97883 100644 --- a/cmd/cloud/organization_test.go +++ b/cmd/cloud/organization_test.go @@ -1278,7 +1278,6 @@ func TestOrganizationTokenUpdate(t *testing.T) { assert.NoError(t, err) mockClient.AssertExpectations(t) }) - t.Run("token is created with no ID provided", func(t *testing.T) { testUtil.InitTestConfig(testUtil.LocalPlatform) mockClient := new(astrocore_mocks.ClientWithResponsesInterface) From c1ba7747ab7ea92eaabb4730b33462ee34fd5bad Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 11:33:33 -0400 Subject: [PATCH 24/26] lint --- cloud/deployment/deployment_token.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index 0bbc1d2b8..2e85e46af 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -4,7 +4,6 @@ import ( httpContext "context" "errors" "fmt" - "golang.org/x/exp/slices" "io" "os" "strconv" @@ -18,6 +17,7 @@ import ( "github.com/astronomer/astro-cli/pkg/ansi" "github.com/astronomer/astro-cli/pkg/input" "github.com/astronomer/astro-cli/pkg/printutil" + "golang.org/x/exp/slices" ) func newTokenTableOut() *printutil.Table { From 4fe24124102bde615415e833dd3c5154bf2ea088 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 9 Apr 2024 12:56:44 -0400 Subject: [PATCH 25/26] improve test coverage --- cloud/deployment/deployment_token_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cloud/deployment/deployment_token_test.go b/cloud/deployment/deployment_token_test.go index 857b29cee..5c00ebcc9 100644 --- a/cloud/deployment/deployment_token_test.go +++ b/cloud/deployment/deployment_token_test.go @@ -26,14 +26,14 @@ var ( fullName2 = "User 2" token = "token" - iamAPIOrgnaizationToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIOrgnaizationToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "ORGANIZATION", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "ORGANIZATION", EntityId: "test-org-id", Role: "ORGANIZATION_MEMBER"}, {EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "WORKSPACE", EntityId: "WORKSPACE", Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}, {EntityType: "DEPLOYMENT", EntityId: deploymentID, Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOKOrganizationToken = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ StatusCode: 200, }, JSON200: &iamAPIOrgnaizationToken, } - iamAPIWorkspaceToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} + iamAPIWorkspaceToken = astroiamcore.ApiToken{Id: "token1", Name: "Token 1", Token: &token, Description: description1, Type: "WORKSPACE", Roles: &[]astroiamcore.ApiTokenRole{{EntityType: "WORKSPACE", EntityId: workspaceID, Role: "WORKSPACE_AUTHOR"}, {EntityType: "DEPLOYMENT", EntityId: "DEPLOYMENT", Role: "DEPLOYMENT_ADMIN"}, {EntityType: "DEPLOYMENT", EntityId: deploymentID, Role: "DEPLOYMENT_ADMIN"}}, CreatedAt: time.Now(), CreatedBy: &astroiamcore.BasicSubjectProfile{FullName: &fullName1}} GetAPITokensResponseOKWorkspaceToken = astroiamcore.GetApiTokenResponse{ HTTPResponse: &http.Response{ From 124c82af6eea147d71e065e8f2e2c1e9fa416ec1 Mon Sep 17 00:00:00 2001 From: Alex Liotta Date: Tue, 16 Apr 2024 10:22:24 -0400 Subject: [PATCH 26/26] pr review comments --- cloud/deployment/deployment_token.go | 124 +++++++++++---------- cloud/organization/organization_token.go | 30 +++--- cloud/team/team.go | 72 ++++++------- cloud/user/user.go | 66 ++++++------ cloud/workspace-token/workspace_token.go | 130 +++++++++++------------ cmd/cloud/deployment.go | 2 +- 6 files changed, 210 insertions(+), 214 deletions(-) diff --git a/cloud/deployment/deployment_token.go b/cloud/deployment/deployment_token.go index 2e85e46af..251379111 100644 --- a/cloud/deployment/deployment_token.go +++ b/cloud/deployment/deployment_token.go @@ -10,9 +10,9 @@ import ( "time" astrocore "github.com/astronomer/astro-cli/astro-client-core" - astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" "github.com/astronomer/astro-cli/cloud/organization" - workspace2 "github.com/astronomer/astro-cli/cloud/workspace-token" + workspaceService "github.com/astronomer/astro-cli/cloud/workspace-token" "github.com/astronomer/astro-cli/context" "github.com/astronomer/astro-cli/pkg/ansi" "github.com/astronomer/astro-cli/pkg/input" @@ -49,8 +49,8 @@ const ( ) // List all deployment Tokens -func ListTokens(client astrocore.CoreClient, deployment string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, out io.Writer) error { - apiTokens, err := getDeploymentTokens(deployment, tokenTypes, client) +func ListTokens(client astrocore.CoreClient, deploymentID string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, out io.Writer) error { + apiTokens, err := getDeploymentTokens(deploymentID, tokenTypes, client) if err != nil { return err } @@ -63,7 +63,7 @@ func ListTokens(client astrocore.CoreClient, deployment string, tokenTypes *[]as scope := apiTokens[i].Type var role string for j := range apiTokens[i].Roles { - if apiTokens[i].Roles[j].EntityId == deployment { + if apiTokens[i].Roles[j].EntityId == deploymentID { role = apiTokens[i].Roles[j].Role } } @@ -83,7 +83,7 @@ func ListTokens(client astrocore.CoreClient, deployment string, tokenTypes *[]as } // create a deployment token -func CreateToken(name, description, role, deployment string, expiration int, cleanOutput bool, out io.Writer, client astrocore.CoreClient) error { +func CreateToken(name, description, role, deploymentID string, expiration int, cleanOutput bool, out io.Writer, client astrocore.CoreClient) error { if name == "" { return ErrInvalidTokenName } @@ -100,7 +100,7 @@ func CreateToken(name, description, role, deployment string, expiration int, cle if expiration != 0 { CreateDeploymentAPITokenRequest.TokenExpiryPeriodInDays = &expiration } - resp, err := client.CreateDeploymentApiTokenWithResponse(httpContext.Background(), ctx.Organization, deployment, CreateDeploymentAPITokenRequest) + resp, err := client.CreateDeploymentApiTokenWithResponse(httpContext.Background(), ctx.Organization, deploymentID, CreateDeploymentAPITokenRequest) if err != nil { return err } @@ -121,7 +121,7 @@ func CreateToken(name, description, role, deployment string, expiration int, cle } // Update a deployment token -func UpdateToken(id, name, newName, description, role, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func UpdateToken(id, name, newName, description, role, deploymentID string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -130,7 +130,7 @@ func UpdateToken(id, name, newName, description, role, deployment string, out io "DEPLOYMENT", } organizationID := ctx.Organization - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deploymentID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -154,7 +154,7 @@ func UpdateToken(id, name, newName, description, role, deployment string, out io if role == "" { for i := range roles { - if roles[i].EntityType == deploymentEntity && roles[i].EntityId == deployment { + if roles[i].EntityType == deploymentEntity && roles[i].EntityId == deploymentID { role = roles[i].Role } } @@ -163,7 +163,7 @@ func UpdateToken(id, name, newName, description, role, deployment string, out io UpdateDeploymentAPITokenRequest.Role = role } - resp, err := client.UpdateDeploymentApiTokenWithResponse(httpContext.Background(), ctx.Organization, deployment, apiTokenID, UpdateDeploymentAPITokenRequest) + resp, err := client.UpdateDeploymentApiTokenWithResponse(httpContext.Background(), ctx.Organization, deploymentID, apiTokenID, UpdateDeploymentAPITokenRequest) if err != nil { return err } @@ -176,7 +176,7 @@ func UpdateToken(id, name, newName, description, role, deployment string, out io } // rotate a deployment API token -func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func RotateToken(id, name, deploymentID string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -185,7 +185,7 @@ func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Wr "DEPLOYMENT", } organizationID := ctx.Organization - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deploymentID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -201,7 +201,7 @@ func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Wr return nil } } - resp, err := client.RotateDeploymentApiTokenWithResponse(httpContext.Background(), ctx.Organization, deployment, apiTokenID) + resp, err := client.RotateDeploymentApiTokenWithResponse(httpContext.Background(), ctx.Organization, deploymentID, apiTokenID) if err != nil { return err } @@ -222,7 +222,7 @@ func RotateToken(id, name, deployment string, cleanOutput, force bool, out io.Wr } // delete a deployments api token -func DeleteToken(id, name, deployment string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func DeleteToken(id, name, deploymentID string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -234,7 +234,7 @@ func DeleteToken(id, name, deployment string, force bool, out io.Writer, client "DEPLOYMENT", } - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deploymentID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -250,7 +250,7 @@ func DeleteToken(id, name, deployment string, force bool, out io.Writer, client } } - resp, err := client.DeleteDeploymentApiTokenWithResponse(httpContext.Background(), organizationID, deployment, apiTokenID) + resp, err := client.DeleteDeploymentApiTokenWithResponse(httpContext.Background(), organizationID, deploymentID, apiTokenID) if err != nil { return err } @@ -263,7 +263,7 @@ func DeleteToken(id, name, deployment string, force bool, out io.Writer, client return nil } -func selectTokens(deployment string, apiTokens []astrocore.ApiToken) (astrocore.ApiToken, error) { +func selectTokens(deploymentID string, apiTokens []astrocore.ApiToken) (astrocore.ApiToken, error) { apiTokensMap := map[string]astrocore.ApiToken{} tab := newTokenSelectionTableOut() for i := range apiTokens { @@ -273,7 +273,7 @@ func selectTokens(deployment string, apiTokens []astrocore.ApiToken) (astrocore. scope := apiTokens[i].Type var role string for j := range apiTokens[i].Roles { - if apiTokens[i].Roles[j].EntityId == deployment { + if apiTokens[i].Roles[j].EntityId == deploymentID { role = apiTokens[i].Roles[j].Role } } @@ -311,13 +311,13 @@ func selectTokens(deployment string, apiTokens []astrocore.ApiToken) (astrocore. } // get all deployment tokens -func getDeploymentTokens(deployment string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, client astrocore.CoreClient) ([]astrocore.ApiToken, error) { +func getDeploymentTokens(deploymentID string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, client astrocore.CoreClient) ([]astrocore.ApiToken, error) { ctx, err := context.GetCurrentContext() if err != nil { return []astrocore.ApiToken{}, err } - resp, err := client.ListDeploymentApiTokensWithResponse(httpContext.Background(), ctx.Organization, deployment, &astrocore.ListDeploymentApiTokensParams{TokenTypes: tokenTypes}) + resp, err := client.ListDeploymentApiTokensWithResponse(httpContext.Background(), ctx.Organization, deploymentID, &astrocore.ListDeploymentApiTokensParams{TokenTypes: tokenTypes}) if err != nil { return []astrocore.ApiToken{}, err } @@ -331,11 +331,11 @@ func getDeploymentTokens(deployment string, tokenTypes *[]astrocore.ListDeployme return APITokens, nil } -func getDeploymentToken(id, name, deployment, message string, tokens []astrocore.ApiToken) (token astrocore.ApiToken, err error) { //nolint:gocognit +func getDeploymentToken(id, name, deploymentID, message string, tokens []astrocore.ApiToken) (token astrocore.ApiToken, err error) { //nolint:gocognit switch { case id == "" && name == "": fmt.Println(message) - token, err = selectTokens(deployment, tokens) + token, err = selectTokens(deploymentID, tokens) if err != nil { return astrocore.ApiToken{}, err } @@ -359,7 +359,7 @@ func getDeploymentToken(id, name, deployment, message string, tokens []astrocore token = matchedTokens[0] } else if len(matchedTokens) > 1 { fmt.Printf("\nThere are more than one API tokens with name %s. Please select an API token:\n", name) - token, err = selectTokens(deployment, matchedTokens) + token, err = selectTokens(deploymentID, matchedTokens) if err != nil { return astrocore.ApiToken{}, err } @@ -389,25 +389,25 @@ func TimeAgo(date time.Time) string { } } -func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func getTokenByID(id, orgID string, client astroiamcore.CoreClient) (token astroiamcore.ApiToken, err error) { resp, err := client.GetApiTokenWithResponse(httpContext.Background(), orgID, id) if err != nil { - return astrocoreiam.ApiToken{}, err + return astroiamcore.ApiToken{}, err } - err = astrocoreiam.NormalizeAPIError(resp.HTTPResponse, resp.Body) + err = astroiamcore.NormalizeAPIError(resp.HTTPResponse, resp.Body) if err != nil { - return astrocoreiam.ApiToken{}, err + return astroiamcore.ApiToken{}, err } return *resp.JSON200, nil } -func GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func GetDeploymentTokenFromInputOrUser(id, name, deploymentID, organizationID string, tokenTypes *[]astrocore.ListDeploymentApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) (token astroiamcore.ApiToken, err error) { if id == "" { - tokens, err := getDeploymentTokens(deployment, tokenTypes, client) + tokens, err := getDeploymentTokens(deploymentID, tokenTypes, client) if err != nil { return token, err } - tokenFromList, err := getDeploymentToken(id, name, deployment, "\nPlease select the Organization API token you would like to update:", tokens) + tokenFromList, err := getDeploymentToken(id, name, deploymentID, "\nPlease select the Organization API token you would like to update:", tokens) if err != nil { return token, err } @@ -422,22 +422,20 @@ func GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID stri } } - if tokenTypes != nil { // verify the user has passed in an id that matches the operations expected token type - if len(*tokenTypes) > 0 { - stringTokenTypes := []string{} - for _, tokenType := range *tokenTypes { - stringTokenTypes = append(stringTokenTypes, string(tokenType)) - } - if !slices.Contains(stringTokenTypes, string(token.Type)) { - return token, errWrongTokenTypeSelected - } + if tokenTypes != nil && len(*tokenTypes) > 0 { // verify the user has passed in an id that matches the operations expected token type + stringTokenTypes := []string{} + for _, tokenType := range *tokenTypes { + stringTokenTypes = append(stringTokenTypes, string(tokenType)) + } + if !slices.Contains(stringTokenTypes, string(token.Type)) { + return token, errWrongTokenTypeSelected } } return token, err } -func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func RemoveOrgTokenDeploymentRole(id, name, deploymentID string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -446,7 +444,7 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ "ORGANIZATION", } - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deploymentID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -457,7 +455,7 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} for i := range roles { - if roles[i].EntityId == deployment { + if roles[i].EntityId == deploymentID { continue // this removes the role in question } @@ -502,7 +500,7 @@ func RemoveOrgTokenDeploymentRole(id, name, deployment string, out io.Writer, cl return nil } -func RemoveWorkspaceTokenDeploymentRole(id, name, workspace, deployment string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func RemoveWorkspaceTokenDeploymentRole(id, name, workspaceID, deploymentID string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -510,13 +508,13 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace, deployment string, organizationID := ctx.Organization - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{ "WORKSPACE", } - token, err := GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) + token, err := GetDeploymentTokenFromInputOrUser(id, name, deploymentID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -527,7 +525,7 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace, deployment string, apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} for i := range roles { - if roles[i].EntityId == deployment { + if roles[i].EntityId == deploymentID { continue // this removes the role in question } @@ -552,7 +550,7 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace, deployment string, Roles: &updateWorkspaceAPITokenRoles, } - resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID, updateWorkspaceAPITokenRequest) + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspaceID, apiTokenID, updateWorkspaceAPITokenRequest) if err != nil { return err } @@ -564,7 +562,7 @@ func RemoveWorkspaceTokenDeploymentRole(id, name, workspace, deployment string, return nil } -func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, operation string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspaceID, deploymentID, operation string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -572,20 +570,20 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o organizationID := ctx.Organization - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } - var token astrocoreiam.ApiToken + var token astroiamcore.ApiToken if operation == "create" { tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} - token, err = workspace2.GetTokenFromInputOrUser(id, name, workspace, organizationID, &tokenTypes, client, iamClient) + token, err = workspaceService.GetTokenFromInputOrUser(id, name, workspaceID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } } else { tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{"WORKSPACE"} - token, err = GetDeploymentTokenFromInputOrUser(id, name, deployment, organizationID, &tokenTypes, client, iamClient) + token, err = GetDeploymentTokenFromInputOrUser(id, name, deploymentID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -594,14 +592,14 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o apiTokenID := token.Id var workspaceRole string apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: deployment, + EntityId: deploymentID, Role: role, } apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} for i := range *token.Roles { roles := *token.Roles - if roles[i].EntityId == deployment { + if roles[i].EntityId == deploymentID { if roles[i].Role == role { return errWorkspaceTokenInDeployment } else { @@ -630,7 +628,7 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o Roles: &updateWorkspaceAPITokenRoles, } - resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID, updateWorkspaceAPITokenRequest) + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspaceID, apiTokenID, updateWorkspaceAPITokenRequest) if err != nil { return err } @@ -642,12 +640,12 @@ func UpsertWorkspaceTokenDeploymentRole(id, name, role, workspace, deployment, o return nil } -func UpsertOrgTokenDeploymentRole(id, name, role, deployment, operation string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func UpsertOrgTokenDeploymentRole(id, name, role, deploymentID, operation string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - var token astrocoreiam.ApiToken + var token astroiamcore.ApiToken if operation == "create" { token, err = organization.GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) if err != nil { @@ -655,7 +653,7 @@ func UpsertOrgTokenDeploymentRole(id, name, role, deployment, operation string, } } else { tokenTypes := []astrocore.ListDeploymentApiTokensParamsTokenTypes{"ORGANIZATION"} - token, err = GetDeploymentTokenFromInputOrUser(id, name, deployment, ctx.Organization, &tokenTypes, client, iamClient) + token, err = GetDeploymentTokenFromInputOrUser(id, name, deploymentID, ctx.Organization, &tokenTypes, client, iamClient) if err != nil { return err } @@ -665,13 +663,13 @@ func UpsertOrgTokenDeploymentRole(id, name, role, deployment, operation string, var orgRole string apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} apiTokenDeploymentRole := astrocore.ApiTokenDeploymentRoleRequest{ - EntityId: deployment, + EntityId: deploymentID, Role: role, } apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{apiTokenDeploymentRole} roles := *token.Roles for i := range roles { - if roles[i].EntityId == deployment { + if roles[i].EntityId == deploymentID { if roles[i].Role == role { return errOrgTokenInDeployment } else { diff --git a/cloud/organization/organization_token.go b/cloud/organization/organization_token.go index 9743dbeba..2d36e4885 100644 --- a/cloud/organization/organization_token.go +++ b/cloud/organization/organization_token.go @@ -10,7 +10,7 @@ import ( "time" astrocore "github.com/astronomer/astro-cli/astro-client-core" - astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" "github.com/astronomer/astro-cli/cloud/user" "github.com/astronomer/astro-cli/context" "github.com/astronomer/astro-cli/pkg/ansi" @@ -53,7 +53,7 @@ func newTokenSelectionTableOut() *printutil.Table { } } -func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func AddOrgTokenToWorkspace(id, name, role, workspaceID string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { err := user.IsWorkspaceRoleValid(role) if err != nil { return err @@ -62,8 +62,8 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } token, err := GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) if err != nil { @@ -73,14 +73,14 @@ func AddOrgTokenToWorkspace(id, name, role, workspace string, out io.Writer, cli var orgRole string apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} apiTokenWorkspaceRole := astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: workspace, + EntityId: workspaceID, Role: role, } apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} roles := *token.Roles for i := range roles { - if roles[i].EntityId == workspace { + if roles[i].EntityId == workspaceID { if roles[i].Role == role { return errOrgTokenInWorkspace } else { @@ -264,19 +264,19 @@ func ListTokens(client astrocore.CoreClient, out io.Writer) error { return nil } -func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func getTokenByID(id, orgID string, client astroiamcore.CoreClient) (token astroiamcore.ApiToken, err error) { resp, err := client.GetApiTokenWithResponse(httpContext.Background(), orgID, id) if err != nil { - return astrocoreiam.ApiToken{}, err + return astroiamcore.ApiToken{}, err } - err = astrocoreiam.NormalizeAPIError(resp.HTTPResponse, resp.Body) + err = astroiamcore.NormalizeAPIError(resp.HTTPResponse, resp.Body) if err != nil { - return astrocoreiam.ApiToken{}, err + return astroiamcore.ApiToken{}, err } return *resp.JSON200, nil } -func GetTokenFromInputOrUser(id, name, organization string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func GetTokenFromInputOrUser(id, name, organization string, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) (token astroiamcore.ApiToken, err error) { if id == "" { tokens, err := getOrganizationTokens(client) if err != nil { @@ -303,7 +303,7 @@ func GetTokenFromInputOrUser(id, name, organization string, client astrocore.Cor } // List all roles for a given organization Token -func ListTokenRoles(id string, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient, out io.Writer) (err error) { +func ListTokenRoles(id string, client astrocore.CoreClient, iamClient astroiamcore.CoreClient, out io.Writer) (err error) { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -367,7 +367,7 @@ func CreateToken(name, description, role string, expiration int, cleanOutput boo } // Update a organization token -func UpdateToken(id, name, newName, description, role string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func UpdateToken(id, name, newName, description, role string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -449,7 +449,7 @@ func UpdateToken(id, name, newName, description, role string, out io.Writer, cli } // rotate a organization API token -func RotateToken(id, name string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func RotateToken(id, name string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -491,7 +491,7 @@ func RotateToken(id, name string, cleanOutput, force bool, out io.Writer, client } // delete a organizations api token -func DeleteToken(id, name string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func DeleteToken(id, name string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err diff --git a/cloud/team/team.go b/cloud/team/team.go index 0bdf2af19..5d14168f6 100644 --- a/cloud/team/team.go +++ b/cloud/team/team.go @@ -90,7 +90,7 @@ func GetTeam(client astrocore.CoreClient, teamID string) (team astrocore.Team, e return team, nil } -func UpdateWorkspaceTeamRole(id, role, workspace string, out io.Writer, client astrocore.CoreClient) error { +func UpdateWorkspaceTeamRole(id, role, workspaceID string, out io.Writer, client astrocore.CoreClient) error { err := user.IsWorkspaceRoleValid(role) if err != nil { return err @@ -99,13 +99,13 @@ func UpdateWorkspaceTeamRole(id, role, workspace string, out io.Writer, client a if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } var team astrocore.Team if id == "" { - teams, err := GetWorkspaceTeams(client, workspace, teamPagnationLimit) + teams, err := GetWorkspaceTeams(client, workspaceID, teamPagnationLimit) if err != nil { return err } @@ -129,7 +129,7 @@ func UpdateWorkspaceTeamRole(id, role, workspace string, out io.Writer, client a teamID := team.Id teamMutateRequest := astrocore.MutateWorkspaceTeamRoleRequest{Role: role} - resp, err := client.MutateWorkspaceTeamRoleWithResponse(httpContext.Background(), ctx.Organization, workspace, teamID, teamMutateRequest) + resp, err := client.MutateWorkspaceTeamRoleWithResponse(httpContext.Background(), ctx.Organization, workspaceID, teamID, teamMutateRequest) if err != nil { return err } @@ -220,18 +220,18 @@ func UpdateTeam(id, name, description, role string, out io.Writer, client astroc return nil } -func RemoveWorkspaceTeam(id, workspace string, out io.Writer, client astrocore.CoreClient) error { +func RemoveWorkspaceTeam(id, workspaceID string, out io.Writer, client astrocore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } var team astrocore.Team if id == "" { - teams, err := GetWorkspaceTeams(client, workspace, teamPagnationLimit) + teams, err := GetWorkspaceTeams(client, workspaceID, teamPagnationLimit) if err != nil { return err } @@ -293,7 +293,7 @@ func selectTeam(teams []astrocore.Team) (astrocore.Team, error) { return selected, nil } -func GetWorkspaceTeams(client astrocore.CoreClient, workspace string, limit int) ([]astrocore.Team, error) { +func GetWorkspaceTeams(client astrocore.CoreClient, workspaceID string, limit int) ([]astrocore.Team, error) { offset := 0 var teams []astrocore.Team @@ -301,11 +301,11 @@ func GetWorkspaceTeams(client astrocore.CoreClient, workspace string, limit int) if err != nil { return nil, err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } for { - resp, err := client.ListWorkspaceTeamsWithResponse(httpContext.Background(), ctx.Organization, workspace, &astrocore.ListWorkspaceTeamsParams{ + resp, err := client.ListWorkspaceTeamsWithResponse(httpContext.Background(), ctx.Organization, workspaceID, &astrocore.ListWorkspaceTeamsParams{ Offset: &offset, Limit: &limit, }) @@ -329,19 +329,19 @@ func GetWorkspaceTeams(client astrocore.CoreClient, workspace string, limit int) } // Prints a list of all of an organizations teams -func ListWorkspaceTeams(out io.Writer, client astrocore.CoreClient, workspace string) error { +func ListWorkspaceTeams(out io.Writer, client astrocore.CoreClient, workspaceID string) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } table := printutil.Table{ DynamicPadding: true, Header: []string{"ID", "Role", "Name", "Description", "Create Date"}, } - teams, err := GetWorkspaceTeams(client, workspace, teamPagnationLimit) + teams, err := GetWorkspaceTeams(client, workspaceID, teamPagnationLimit) if err != nil { return err } @@ -353,7 +353,7 @@ func ListWorkspaceTeams(out io.Writer, client astrocore.CoreClient, workspace st roles = *teams[i].Roles } for _, role := range roles { - if role.EntityType == "WORKSPACE" && role.EntityId == workspace { + if role.EntityType == "WORKSPACE" && role.EntityId == workspaceID { teamRole = role.Role } } @@ -374,7 +374,7 @@ func ListWorkspaceTeams(out io.Writer, client astrocore.CoreClient, workspace st return nil } -func AddWorkspaceTeam(id, role, workspace string, out io.Writer, client astrocore.CoreClient) error { +func AddWorkspaceTeam(id, role, workspaceID string, out io.Writer, client astrocore.CoreClient) error { err := user.IsWorkspaceRoleValid(role) if err != nil { return err @@ -383,8 +383,8 @@ func AddWorkspaceTeam(id, role, workspace string, out io.Writer, client astrocor if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } var team astrocore.Team if id == "" { @@ -416,7 +416,7 @@ func AddWorkspaceTeam(id, role, workspace string, out io.Writer, client astrocor mutateUserInput := astrocore.MutateWorkspaceTeamRoleRequest{ Role: role, } - resp, err := client.MutateWorkspaceTeamRoleWithResponse(httpContext.Background(), ctx.Organization, workspace, teamID, mutateUserInput) + resp, err := client.MutateWorkspaceTeamRoleWithResponse(httpContext.Background(), ctx.Organization, workspaceID, teamID, mutateUserInput) if err != nil { return err } @@ -771,7 +771,7 @@ func ListTeamUsers(teamID string, out io.Writer, client astrocore.CoreClient) (e return nil } -func GetDeploymentTeams(client astrocore.CoreClient, deployment string, limit int) ([]astrocore.Team, error) { +func GetDeploymentTeams(client astrocore.CoreClient, deploymentID string, limit int) ([]astrocore.Team, error) { offset := 0 var teams []astrocore.Team ctx, err := context.GetCurrentContext() @@ -780,7 +780,7 @@ func GetDeploymentTeams(client astrocore.CoreClient, deployment string, limit in } includeDeploymentRoles := true for { - resp, err := client.ListDeploymentTeamsWithResponse(httpContext.Background(), ctx.Organization, deployment, &astrocore.ListDeploymentTeamsParams{ + resp, err := client.ListDeploymentTeamsWithResponse(httpContext.Background(), ctx.Organization, deploymentID, &astrocore.ListDeploymentTeamsParams{ IncludeDeploymentRoles: &includeDeploymentRoles, Offset: &offset, Limit: &limit, @@ -805,12 +805,12 @@ func GetDeploymentTeams(client astrocore.CoreClient, deployment string, limit in } // Prints a list of all of an organizations teams -func ListDeploymentTeams(out io.Writer, client astrocore.CoreClient, deployment string) error { +func ListDeploymentTeams(out io.Writer, client astrocore.CoreClient, deploymentID string) error { table := printutil.Table{ DynamicPadding: true, Header: []string{"ID", "Role", "Name", "Description", "Create Date"}, } - teams, err := GetDeploymentTeams(client, deployment, teamPagnationLimit) + teams, err := GetDeploymentTeams(client, deploymentID, teamPagnationLimit) if err != nil { return err } @@ -826,7 +826,7 @@ func ListDeploymentTeams(out io.Writer, client astrocore.CoreClient, deployment roles = *teams[i].Roles } for _, role := range roles { - if role.EntityType == "DEPLOYMENT" && role.EntityId == deployment { + if role.EntityType == "DEPLOYMENT" && role.EntityId == deploymentID { teamRole = role.Role } } @@ -843,7 +843,7 @@ func ListDeploymentTeams(out io.Writer, client astrocore.CoreClient, deployment return nil } -func AddDeploymentTeam(id, role, deployment string, out io.Writer, client astrocore.CoreClient) error { +func AddDeploymentTeam(id, role, deploymentID string, out io.Writer, client astrocore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -879,7 +879,7 @@ func AddDeploymentTeam(id, role, deployment string, out io.Writer, client astroc mutateDeploymentTeamInput := astrocore.MutateDeploymentTeamRoleRequest{ Role: role, } - resp, err := client.MutateDeploymentTeamRoleWithResponse(httpContext.Background(), ctx.Organization, deployment, teamID, mutateDeploymentTeamInput) + resp, err := client.MutateDeploymentTeamRoleWithResponse(httpContext.Background(), ctx.Organization, deploymentID, teamID, mutateDeploymentTeamInput) if err != nil { return err } @@ -891,7 +891,7 @@ func AddDeploymentTeam(id, role, deployment string, out io.Writer, client astroc return nil } -func UpdateDeploymentTeamRole(id, role, deployment string, out io.Writer, client astrocore.CoreClient) error { +func UpdateDeploymentTeamRole(id, role, deploymentID string, out io.Writer, client astrocore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -899,7 +899,7 @@ func UpdateDeploymentTeamRole(id, role, deployment string, out io.Writer, client var team astrocore.Team if id == "" { - teams, err := GetDeploymentTeams(client, deployment, teamPagnationLimit) + teams, err := GetDeploymentTeams(client, deploymentID, teamPagnationLimit) if err != nil { return err } @@ -923,7 +923,7 @@ func UpdateDeploymentTeamRole(id, role, deployment string, out io.Writer, client teamID := team.Id teamMutateRequest := astrocore.MutateDeploymentTeamRoleRequest{Role: role} - resp, err := client.MutateDeploymentTeamRoleWithResponse(httpContext.Background(), ctx.Organization, deployment, teamID, teamMutateRequest) + resp, err := client.MutateDeploymentTeamRoleWithResponse(httpContext.Background(), ctx.Organization, deploymentID, teamID, teamMutateRequest) if err != nil { return err } @@ -935,7 +935,7 @@ func UpdateDeploymentTeamRole(id, role, deployment string, out io.Writer, client return nil } -func RemoveDeploymentTeam(id, deployment string, out io.Writer, client astrocore.CoreClient) error { +func RemoveDeploymentTeam(id, deploymentID string, out io.Writer, client astrocore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -943,7 +943,7 @@ func RemoveDeploymentTeam(id, deployment string, out io.Writer, client astrocore var team astrocore.Team if id == "" { - teams, err := GetDeploymentTeams(client, deployment, teamPagnationLimit) + teams, err := GetDeploymentTeams(client, deploymentID, teamPagnationLimit) if err != nil { return err } @@ -965,7 +965,7 @@ func RemoveDeploymentTeam(id, deployment string, out io.Writer, client astrocore } } teamID := team.Id - resp, err := client.DeleteDeploymentTeamWithResponse(httpContext.Background(), ctx.Organization, deployment, teamID) + resp, err := client.DeleteDeploymentTeamWithResponse(httpContext.Background(), ctx.Organization, deploymentID, teamID) if err != nil { return err } @@ -973,6 +973,6 @@ func RemoveDeploymentTeam(id, deployment string, out io.Writer, client astrocore if err != nil { return err } - fmt.Fprintf(out, "Astro Team %s was successfully removed from deployment %s\n", team.Name, deployment) + fmt.Fprintf(out, "Astro Team %s was successfully removed from deployment %s\n", team.Name, deploymentID) return nil } diff --git a/cloud/user/user.go b/cloud/user/user.go index 841bf3de0..576200019 100644 --- a/cloud/user/user.go +++ b/cloud/user/user.go @@ -252,7 +252,7 @@ func ListOrgUsers(out io.Writer, client astrocore.CoreClient) error { return nil } -func AddWorkspaceUser(email, role, workspace string, out io.Writer, client astrocore.CoreClient) error { +func AddWorkspaceUser(email, role, workspaceID string, out io.Writer, client astrocore.CoreClient) error { err := IsWorkspaceRoleValid(role) if err != nil { return err @@ -261,8 +261,8 @@ func AddWorkspaceUser(email, role, workspace string, out io.Writer, client astro if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } // Get all org users. Setting limit to 1000 for now users, err := GetOrgUsers(client) @@ -276,7 +276,7 @@ func AddWorkspaceUser(email, role, workspace string, out io.Writer, client astro mutateUserInput := astrocore.MutateWorkspaceUserRoleRequest{ Role: role, } - resp, err := client.MutateWorkspaceUserRoleWithResponse(httpContext.Background(), ctx.Organization, workspace, userID, mutateUserInput) + resp, err := client.MutateWorkspaceUserRoleWithResponse(httpContext.Background(), ctx.Organization, workspaceID, userID, mutateUserInput) if err != nil { return err } @@ -288,7 +288,7 @@ func AddWorkspaceUser(email, role, workspace string, out io.Writer, client astro return nil } -func UpdateWorkspaceUserRole(email, role, workspace string, out io.Writer, client astrocore.CoreClient) error { +func UpdateWorkspaceUserRole(email, role, workspaceID string, out io.Writer, client astrocore.CoreClient) error { err := IsWorkspaceRoleValid(role) if err != nil { return err @@ -297,11 +297,11 @@ func UpdateWorkspaceUserRole(email, role, workspace string, out io.Writer, clien if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } // Get all org users. Setting limit to 1000 for now - users, err := GetWorkspaceUsers(client, workspace, userPagnationLimit) + users, err := GetWorkspaceUsers(client, workspaceID, userPagnationLimit) if err != nil { return err } @@ -312,8 +312,8 @@ func UpdateWorkspaceUserRole(email, role, workspace string, out io.Writer, clien mutateUserInput := astrocore.MutateWorkspaceUserRoleRequest{ Role: role, } - fmt.Println("workspace: " + workspace) - resp, err := client.MutateWorkspaceUserRoleWithResponse(httpContext.Background(), ctx.Organization, workspace, userID, mutateUserInput) + fmt.Println("workspace: " + workspaceID) + resp, err := client.MutateWorkspaceUserRoleWithResponse(httpContext.Background(), ctx.Organization, workspaceID, userID, mutateUserInput) if err != nil { fmt.Println("error in MutateWorkspaceUserRoleWithResponse") return err @@ -353,7 +353,7 @@ func IsOrganizationRoleValid(role string) error { } // Returns a list of all of a worksapces users -func GetWorkspaceUsers(client astrocore.CoreClient, workspace string, limit int) ([]astrocore.User, error) { +func GetWorkspaceUsers(client astrocore.CoreClient, workspaceID string, limit int) ([]astrocore.User, error) { offset := 0 var users []astrocore.User @@ -362,11 +362,11 @@ func GetWorkspaceUsers(client astrocore.CoreClient, workspace string, limit int) return nil, err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } for { - resp, err := client.ListWorkspaceUsersWithResponse(httpContext.Background(), ctx.Organization, workspace, &astrocore.ListWorkspaceUsersParams{ + resp, err := client.ListWorkspaceUsersWithResponse(httpContext.Background(), ctx.Organization, workspaceID, &astrocore.ListWorkspaceUsersParams{ Offset: &offset, Limit: &limit, }) @@ -392,13 +392,13 @@ func GetWorkspaceUsers(client astrocore.CoreClient, workspace string, limit int) // Prints a list of all of a workspaces users // //nolint:dupl -func ListWorkspaceUsers(out io.Writer, client astrocore.CoreClient, workspace string) error { +func ListWorkspaceUsers(out io.Writer, client astrocore.CoreClient, workspaceID string) error { table := printutil.Table{ Padding: []int{30, 50, 10, 50, 10, 10, 10}, DynamicPadding: true, Header: []string{"FULLNAME", "EMAIL", "ID", "WORKSPACE ROLE", "CREATE DATE"}, } - users, err := GetWorkspaceUsers(client, workspace, userPagnationLimit) + users, err := GetWorkspaceUsers(client, workspaceID, userPagnationLimit) if err != nil { return err } @@ -417,16 +417,16 @@ func ListWorkspaceUsers(out io.Writer, client astrocore.CoreClient, workspace st return nil } -func RemoveWorkspaceUser(email, workspace string, out io.Writer, client astrocore.CoreClient) error { +func RemoveWorkspaceUser(email, workspaceID string, out io.Writer, client astrocore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } // Get all org users. Setting limit to 1000 for now - users, err := GetWorkspaceUsers(client, workspace, userPagnationLimit) + users, err := GetWorkspaceUsers(client, workspaceID, userPagnationLimit) if err != nil { return err } @@ -434,7 +434,7 @@ func RemoveWorkspaceUser(email, workspace string, out io.Writer, client astrocor if err != nil { return err } - resp, err := client.DeleteWorkspaceUserWithResponse(httpContext.Background(), ctx.Organization, workspace, userID) + resp, err := client.DeleteWorkspaceUserWithResponse(httpContext.Background(), ctx.Organization, workspaceID, userID) if err != nil { return err } @@ -484,7 +484,7 @@ func GetUser(client astrocore.CoreClient, userID string) (user astrocore.User, e return user, nil } -func AddDeploymentUser(email, role, deployment string, out io.Writer, client astrocore.CoreClient) error { +func AddDeploymentUser(email, role, deploymentID string, out io.Writer, client astrocore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err @@ -502,7 +502,7 @@ func AddDeploymentUser(email, role, deployment string, out io.Writer, client ast mutateUserInput := astrocore.MutateDeploymentUserRoleRequest{ Role: role, } - resp, err := client.MutateDeploymentUserRoleWithResponse(httpContext.Background(), ctx.Organization, deployment, userID, mutateUserInput) + resp, err := client.MutateDeploymentUserRoleWithResponse(httpContext.Background(), ctx.Organization, deploymentID, userID, mutateUserInput) if err != nil { return err } @@ -514,14 +514,14 @@ func AddDeploymentUser(email, role, deployment string, out io.Writer, client ast return nil } -func UpdateDeploymentUserRole(email, role, deployment string, out io.Writer, client astrocore.CoreClient) error { +func UpdateDeploymentUserRole(email, role, deploymentID string, out io.Writer, client astrocore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } // Get all org users. Setting limit to 1000 for now - users, err := GetDeploymentUsers(client, deployment, userPagnationLimit) + users, err := GetDeploymentUsers(client, deploymentID, userPagnationLimit) if err != nil { return err } @@ -532,7 +532,7 @@ func UpdateDeploymentUserRole(email, role, deployment string, out io.Writer, cli mutateUserInput := astrocore.MutateDeploymentUserRoleRequest{ Role: role, } - resp, err := client.MutateDeploymentUserRoleWithResponse(httpContext.Background(), ctx.Organization, deployment, userID, mutateUserInput) + resp, err := client.MutateDeploymentUserRoleWithResponse(httpContext.Background(), ctx.Organization, deploymentID, userID, mutateUserInput) if err != nil { fmt.Println("error in MutateDeploymentUserRoleWithResponse") return err @@ -545,14 +545,14 @@ func UpdateDeploymentUserRole(email, role, deployment string, out io.Writer, cli return nil } -func RemoveDeploymentUser(email, deployment string, out io.Writer, client astrocore.CoreClient) error { +func RemoveDeploymentUser(email, deploymentID string, out io.Writer, client astrocore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } // Get all org users. Setting limit to 1000 for now - users, err := GetDeploymentUsers(client, deployment, userPagnationLimit) + users, err := GetDeploymentUsers(client, deploymentID, userPagnationLimit) if err != nil { return err } @@ -560,7 +560,7 @@ func RemoveDeploymentUser(email, deployment string, out io.Writer, client astroc if err != nil { return err } - resp, err := client.DeleteDeploymentUserWithResponse(httpContext.Background(), ctx.Organization, deployment, userID) + resp, err := client.DeleteDeploymentUserWithResponse(httpContext.Background(), ctx.Organization, deploymentID, userID) if err != nil { return err } @@ -573,7 +573,7 @@ func RemoveDeploymentUser(email, deployment string, out io.Writer, client astroc } // Returns a list of all of a deployments users -func GetDeploymentUsers(client astrocore.CoreClient, deployment string, limit int) ([]astrocore.User, error) { +func GetDeploymentUsers(client astrocore.CoreClient, deploymentID string, limit int) ([]astrocore.User, error) { offset := 0 var users []astrocore.User @@ -583,7 +583,7 @@ func GetDeploymentUsers(client astrocore.CoreClient, deployment string, limit in } includeDeploymentRoles := true for { - resp, err := client.ListDeploymentUsersWithResponse(httpContext.Background(), ctx.Organization, deployment, &astrocore.ListDeploymentUsersParams{ + resp, err := client.ListDeploymentUsersWithResponse(httpContext.Background(), ctx.Organization, deploymentID, &astrocore.ListDeploymentUsersParams{ IncludeDeploymentRoles: &includeDeploymentRoles, Offset: &offset, Limit: &limit, @@ -610,13 +610,13 @@ func GetDeploymentUsers(client astrocore.CoreClient, deployment string, limit in // Prints a list of all of an deployments users // //nolint:dupl -func ListDeploymentUsers(out io.Writer, client astrocore.CoreClient, deployment string) error { +func ListDeploymentUsers(out io.Writer, client astrocore.CoreClient, deploymentID string) error { table := printutil.Table{ Padding: []int{30, 50, 10, 50, 10, 10, 10}, DynamicPadding: true, Header: []string{"FULLNAME", "EMAIL", "ID", "DEPLOYMENT ROLE", "CREATE DATE"}, } - users, err := GetDeploymentUsers(client, deployment, userPagnationLimit) + users, err := GetDeploymentUsers(client, deploymentID, userPagnationLimit) if err != nil { return err } diff --git a/cloud/workspace-token/workspace_token.go b/cloud/workspace-token/workspace_token.go index 8a2462b1e..b06d4b029 100644 --- a/cloud/workspace-token/workspace_token.go +++ b/cloud/workspace-token/workspace_token.go @@ -11,10 +11,10 @@ import ( "time" astrocore "github.com/astronomer/astro-cli/astro-client-core" - astrocoreiam "github.com/astronomer/astro-cli/astro-client-iam-core" + astroiamcore "github.com/astronomer/astro-cli/astro-client-iam-core" "github.com/astronomer/astro-cli/cloud/organization" "github.com/astronomer/astro-cli/cloud/user" - workspace2 "github.com/astronomer/astro-cli/cloud/workspace" + workspaceService "github.com/astronomer/astro-cli/cloud/workspace" "github.com/astronomer/astro-cli/context" "github.com/astronomer/astro-cli/pkg/ansi" "github.com/astronomer/astro-cli/pkg/input" @@ -50,17 +50,17 @@ const ( ) // List all workspace Tokens -func ListTokens(client astrocore.CoreClient, workspace string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, out io.Writer) error { +func ListTokens(client astrocore.CoreClient, workspaceID string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, out io.Writer) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } - apiTokens, err := getWorkspaceTokens(workspace, tokenTypes, client) + apiTokens, err := getWorkspaceTokens(workspaceID, tokenTypes, client) if err != nil { return err } @@ -73,7 +73,7 @@ func ListTokens(client astrocore.CoreClient, workspace string, tokenTypes *[]ast scope := apiTokens[i].Type var role string for j := range apiTokens[i].Roles { - if apiTokens[i].Roles[j].EntityId == workspace { + if apiTokens[i].Roles[j].EntityId == workspaceID { role = apiTokens[i].Roles[j].Role } } @@ -93,20 +93,20 @@ func ListTokens(client astrocore.CoreClient, workspace string, tokenTypes *[]ast } // create a workspace token -func CreateToken(name, description, role, workspace string, expiration int, cleanOutput bool, out io.Writer, client astrocore.CoreClient) error { +func CreateToken(name, description, role, workspaceID string, expiration int, cleanOutput bool, out io.Writer, client astrocore.CoreClient) error { err := user.IsWorkspaceRoleValid(role) if err != nil { return err } if name == "" { - return workspace2.ErrInvalidTokenName + return workspaceService.ErrInvalidTokenName } ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } CreateWorkspaceAPITokenRequest := astrocore.CreateWorkspaceApiTokenJSONRequestBody{ Description: &description, @@ -116,7 +116,7 @@ func CreateToken(name, description, role, workspace string, expiration int, clea if expiration != 0 { CreateWorkspaceAPITokenRequest.TokenExpiryPeriodInDays = &expiration } - resp, err := client.CreateWorkspaceApiTokenWithResponse(httpContext.Background(), ctx.Organization, workspace, CreateWorkspaceAPITokenRequest) + resp, err := client.CreateWorkspaceApiTokenWithResponse(httpContext.Background(), ctx.Organization, workspaceID, CreateWorkspaceAPITokenRequest) if err != nil { return err } @@ -137,27 +137,27 @@ func CreateToken(name, description, role, workspace string, expiration int, clea } // Update a workspace token -func UpdateToken(id, name, newName, description, role, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func UpdateToken(id, name, newName, description, role, workspaceID string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } organizationID := ctx.Organization tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} - token, err := GetTokenFromInputOrUser(id, name, workspace, organizationID, &tokenTypes, client, iamClient) + token, err := GetTokenFromInputOrUser(id, name, workspaceID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} roles := *token.Roles for i := range roles { - if roles[i].EntityId == workspace { + if roles[i].EntityId == workspaceID { if roles[i].Role == role { return errWorkspaceTokenInDeployment } else { @@ -195,7 +195,7 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. if role == "" { for i := range roles { - if roles[i].EntityType == workspaceEntity && roles[i].EntityId == workspace { + if roles[i].EntityType == workspaceEntity && roles[i].EntityId == workspaceID { role = roles[i].Role } } @@ -212,7 +212,7 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. UpdateWorkspaceAPITokenRequest.Roles.Workspace = &role } - resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID, UpdateWorkspaceAPITokenRequest) + resp, err := client.UpdateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspaceID, apiTokenID, UpdateWorkspaceAPITokenRequest) if err != nil { return err } @@ -225,18 +225,18 @@ func UpdateToken(id, name, newName, description, role, workspace string, out io. } // rotate a workspace API token -func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func RotateToken(id, name, workspaceID string, cleanOutput, force bool, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } organizationID := ctx.Organization tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"WORKSPACE"} - token, err := GetTokenFromInputOrUser(id, name, workspace, organizationID, &tokenTypes, client, iamClient) + token, err := GetTokenFromInputOrUser(id, name, workspaceID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -252,7 +252,7 @@ func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Wri return nil } } - resp, err := client.RotateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID) + resp, err := client.RotateWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspaceID, apiTokenID) if err != nil { return err } @@ -273,16 +273,16 @@ func RotateToken(id, name, workspace string, cleanOutput, force bool, out io.Wri } // delete a workspaces api token -func DeleteToken(id, name, workspace string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func DeleteToken(id, name, workspaceID string, force bool, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } organizationID := ctx.Organization - token, err := GetTokenFromInputOrUser(id, name, workspace, organizationID, nil, client, iamClient) + token, err := GetTokenFromInputOrUser(id, name, workspaceID, organizationID, nil, client, iamClient) if err != nil { return err } @@ -310,7 +310,7 @@ func DeleteToken(id, name, workspace string, force bool, out io.Writer, client a } } - resp, err := client.DeleteWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspace, apiTokenID) + resp, err := client.DeleteWorkspaceApiTokenWithResponse(httpContext.Background(), organizationID, workspaceID, apiTokenID) if err != nil { return err } @@ -326,7 +326,7 @@ func DeleteToken(id, name, workspace string, force bool, out io.Writer, client a return nil } -func selectTokens(workspace string, apiTokens []astrocore.ApiToken) (astrocore.ApiToken, error) { +func selectTokens(workspaceID string, apiTokens []astrocore.ApiToken) (astrocore.ApiToken, error) { apiTokensMap := map[string]astrocore.ApiToken{} tab := newTokenSelectionTableOut() for i := range apiTokens { @@ -336,7 +336,7 @@ func selectTokens(workspace string, apiTokens []astrocore.ApiToken) (astrocore.A scope := apiTokens[i].Type var role string for j := range apiTokens[i].Roles { - if apiTokens[i].Roles[j].EntityId == workspace { + if apiTokens[i].Roles[j].EntityId == workspaceID { role = apiTokens[i].Roles[j].Role } } @@ -374,15 +374,15 @@ func selectTokens(workspace string, apiTokens []astrocore.ApiToken) (astrocore.A } // get all workspace tokens -func getWorkspaceTokens(workspace string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient) ([]astrocore.ApiToken, error) { +func getWorkspaceTokens(workspaceID string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient) ([]astrocore.ApiToken, error) { ctx, err := context.GetCurrentContext() if err != nil { return []astrocore.ApiToken{}, err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } - resp, err := client.ListWorkspaceApiTokensWithResponse(httpContext.Background(), ctx.Organization, workspace, &astrocore.ListWorkspaceApiTokensParams{TokenTypes: tokenTypes}) + resp, err := client.ListWorkspaceApiTokensWithResponse(httpContext.Background(), ctx.Organization, workspaceID, &astrocore.ListWorkspaceApiTokensParams{TokenTypes: tokenTypes}) if err != nil { return []astrocore.ApiToken{}, err } @@ -396,11 +396,11 @@ func getWorkspaceTokens(workspace string, tokenTypes *[]astrocore.ListWorkspaceA return APITokens, nil } -func getWorkspaceToken(id, name, workspace, message string, tokens []astrocore.ApiToken) (token astrocore.ApiToken, err error) { //nolint:gocognit +func getWorkspaceToken(id, name, workspaceID, message string, tokens []astrocore.ApiToken) (token astrocore.ApiToken, err error) { //nolint:gocognit switch { case id == "" && name == "": fmt.Println(message) - token, err = selectTokens(workspace, tokens) + token, err = selectTokens(workspaceID, tokens) if err != nil { return astrocore.ApiToken{}, err } @@ -424,7 +424,7 @@ func getWorkspaceToken(id, name, workspace, message string, tokens []astrocore.A token = matchedTokens[0] } else if len(matchedTokens) > 1 { fmt.Printf("\nThere are more than one API tokens with name %s. Please select an API token:\n", name) - token, err = selectTokens(workspace, matchedTokens) + token, err = selectTokens(workspaceID, matchedTokens) if err != nil { return astrocore.ApiToken{}, err } @@ -454,25 +454,25 @@ func TimeAgo(date time.Time) string { } } -func getTokenByID(id, orgID string, client astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func getTokenByID(id, orgID string, client astroiamcore.CoreClient) (token astroiamcore.ApiToken, err error) { resp, err := client.GetApiTokenWithResponse(httpContext.Background(), orgID, id) if err != nil { - return astrocoreiam.ApiToken{}, err + return astroiamcore.ApiToken{}, err } - err = astrocoreiam.NormalizeAPIError(resp.HTTPResponse, resp.Body) + err = astroiamcore.NormalizeAPIError(resp.HTTPResponse, resp.Body) if err != nil { - return astrocoreiam.ApiToken{}, err + return astroiamcore.ApiToken{}, err } return *resp.JSON200, nil } -func GetTokenFromInputOrUser(id, name, workspace, organizationID string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) (token astrocoreiam.ApiToken, err error) { +func GetTokenFromInputOrUser(id, name, workspaceID, organizationID string, tokenTypes *[]astrocore.ListWorkspaceApiTokensParamsTokenTypes, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) (token astroiamcore.ApiToken, err error) { if id == "" { - tokens, err := getWorkspaceTokens(workspace, tokenTypes, client) + tokens, err := getWorkspaceTokens(workspaceID, tokenTypes, client) if err != nil { return token, err } - tokenFromList, err := getWorkspaceToken(id, name, workspace, "\nPlease select the Workspace API token you would like to add to the Deployment:", tokens) + tokenFromList, err := getWorkspaceToken(id, name, workspaceID, "\nPlease select the Workspace API token you would like to add to the Deployment:", tokens) if err != nil { return token, err } @@ -486,35 +486,33 @@ func GetTokenFromInputOrUser(id, name, workspace, organizationID string, tokenTy return token, err } } - if tokenTypes != nil { // verify the user has passed in an id that matches the operations expected token type - if len(*tokenTypes) > 0 { - stringTokenTypes := []string{} - for _, tokenType := range *tokenTypes { - stringTokenTypes = append(stringTokenTypes, string(tokenType)) - } - if !slices.Contains(stringTokenTypes, string(token.Type)) { - return token, errWrongTokenTypeSelected - } + if tokenTypes != nil && len(*tokenTypes) > 0 { // verify the user has passed in an id that matches the operations expected token type + stringTokenTypes := []string{} + for _, tokenType := range *tokenTypes { + stringTokenTypes = append(stringTokenTypes, string(tokenType)) + } + if !slices.Contains(stringTokenTypes, string(token.Type)) { + return token, errWrongTokenTypeSelected } } return token, err } -func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func RemoveOrgTokenWorkspaceRole(id, name, workspaceID string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } organizationID := ctx.Organization tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{ "ORGANIZATION", } - token, err := GetTokenFromInputOrUser(id, name, workspace, organizationID, &tokenTypes, client, iamClient) + token, err := GetTokenFromInputOrUser(id, name, workspaceID, organizationID, &tokenTypes, client, iamClient) if err != nil { return err } @@ -525,7 +523,7 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{} apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} for i := range roles { - if roles[i].EntityId == workspace { + if roles[i].EntityId == workspaceID { continue // this removes the role in question } @@ -570,16 +568,16 @@ func RemoveOrgTokenWorkspaceRole(id, name, workspace string, out io.Writer, clie return nil } -func UpsertOrgTokenWorkspaceRole(id, name, role, workspace, operation string, out io.Writer, client astrocore.CoreClient, iamClient astrocoreiam.CoreClient) error { +func UpsertOrgTokenWorkspaceRole(id, name, role, workspaceID, operation string, out io.Writer, client astrocore.CoreClient, iamClient astroiamcore.CoreClient) error { ctx, err := context.GetCurrentContext() if err != nil { return err } - if workspace == "" { - workspace = ctx.Workspace + if workspaceID == "" { + workspaceID = ctx.Workspace } - var token astrocoreiam.ApiToken + var token astroiamcore.ApiToken if operation == "create" { token, err = organization.GetTokenFromInputOrUser(id, name, ctx.Organization, client, iamClient) if err != nil { @@ -587,7 +585,7 @@ func UpsertOrgTokenWorkspaceRole(id, name, role, workspace, operation string, ou } } else { tokenTypes := []astrocore.ListWorkspaceApiTokensParamsTokenTypes{"ORGANIZATION"} - token, err = GetTokenFromInputOrUser(id, name, workspace, ctx.Organization, &tokenTypes, client, iamClient) + token, err = GetTokenFromInputOrUser(id, name, workspaceID, ctx.Organization, &tokenTypes, client, iamClient) if err != nil { return err } @@ -596,7 +594,7 @@ func UpsertOrgTokenWorkspaceRole(id, name, role, workspace, operation string, ou apiTokenID := token.Id var orgRole string apiTokenWorkspaceRole := astrocore.ApiTokenWorkspaceRoleRequest{ - EntityId: workspace, + EntityId: workspaceID, Role: role, } apiTokenWorkspaceRoles := []astrocore.ApiTokenWorkspaceRoleRequest{apiTokenWorkspaceRole} @@ -604,7 +602,7 @@ func UpsertOrgTokenWorkspaceRole(id, name, role, workspace, operation string, ou apiTokenDeploymentRoles := []astrocore.ApiTokenDeploymentRoleRequest{} roles := *token.Roles for i := range roles { - if roles[i].EntityId == workspace { + if roles[i].EntityId == workspaceID { if roles[i].Role == role { return errOrgTokenInWorkspace } else { diff --git a/cmd/cloud/deployment.go b/cmd/cloud/deployment.go index ff943034d..bc89cc608 100644 --- a/cmd/cloud/deployment.go +++ b/cmd/cloud/deployment.go @@ -983,7 +983,7 @@ func newDeploymentTokenUpdateCmd(out io.Writer) *cobra.Command { Use: "update [TOKEN_ID]", Aliases: []string{"up"}, Short: "Update a Deployment API token", - Long: "Update a Deployment API token that has a role in an Astro Deployment\n$astro workspace token update [TOKEN_ID] --name [new token name] --role [Possible values are DEPLOYMENT_ADMIN or a custom role name].", + Long: "Update a Deployment API token that has a role in an Astro Deployment\n$astro deployment token update [TOKEN_ID] --name [new token name] --role [Possible values are DEPLOYMENT_ADMIN or a custom role name].", RunE: func(cmd *cobra.Command, args []string) error { return updateDeploymentToken(cmd, args, out) },