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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ require (
github.com/hashicorp/terraform-plugin-go v0.29.0
github.com/hashicorp/terraform-plugin-log v0.10.0
github.com/hashicorp/terraform-plugin-testing v1.14.0
github.com/stackitcloud/stackit-sdk-go/core v0.20.0
github.com/stackitcloud/stackit-sdk-go/core v0.20.1
github.com/stackitcloud/stackit-sdk-go/services/cdn v1.6.0
github.com/stackitcloud/stackit-sdk-go/services/dns v0.17.1
github.com/stackitcloud/stackit-sdk-go/services/git v0.8.0
Expand Down Expand Up @@ -82,7 +82,7 @@ require (
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/oklog/run v1.2.0 // indirect
github.com/stackitcloud/stackit-sdk-go/services/authorization v0.9.0
github.com/stackitcloud/stackit-sdk-go/services/authorization v0.11.0
github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,10 @@ github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=
github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=
github.com/stackitcloud/stackit-sdk-go/core v0.20.0 h1:4rrUk6uT1g4nOn5/g1uXukP07Tux/o5xbMz/f/qE1rY=
github.com/stackitcloud/stackit-sdk-go/core v0.20.0/go.mod h1:fqto7M82ynGhEnpZU6VkQKYWYoFG5goC076JWXTUPRQ=
github.com/stackitcloud/stackit-sdk-go/services/authorization v0.9.0 h1:7ZKd3b+E/R4TEVShLTXxx5FrsuDuJBOyuVOuKTMa4mo=
github.com/stackitcloud/stackit-sdk-go/services/authorization v0.9.0/go.mod h1:/FoXa6hF77Gv8brrvLBCKa5ie1Xy9xn39yfHwaln9Tw=
github.com/stackitcloud/stackit-sdk-go/core v0.20.1 h1:odiuhhRXmxvEvnVTeZSN9u98edvw2Cd3DcnkepncP3M=
github.com/stackitcloud/stackit-sdk-go/core v0.20.1/go.mod h1:fqto7M82ynGhEnpZU6VkQKYWYoFG5goC076JWXTUPRQ=
github.com/stackitcloud/stackit-sdk-go/services/authorization v0.11.0 h1:4YFY5PG4vP/NiEP1uxCwh+kQHEU7iHG6syuFD7NPqcw=
github.com/stackitcloud/stackit-sdk-go/services/authorization v0.11.0/go.mod h1:v4xdRA5P8Vr+zLdHh+ODgspN0WJG04wLImIJoYjrPK4=
github.com/stackitcloud/stackit-sdk-go/services/cdn v1.6.0 h1:Q+qIdejeMsYMkbtVoI9BpGlKGdSVFRBhH/zj44SP8TM=
github.com/stackitcloud/stackit-sdk-go/services/cdn v1.6.0/go.mod h1:YGadfhuy8yoseczTxF7vN4t9ES2WxGQr0Pug14ii7y4=
github.com/stackitcloud/stackit-sdk-go/services/dns v0.17.1 h1:CnhAMLql0MNmAeq4roQKN8OpSKX4FSgTU6Eu6detB4I=
Expand Down
120 changes: 114 additions & 6 deletions stackit/internal/services/authorization/authorization_acc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
_ "embed"

"github.com/hashicorp/terraform-plugin-testing/config"
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
stackitSdkConfig "github.com/stackitcloud/stackit-sdk-go/core/config"
Expand All @@ -33,12 +34,33 @@ var invalidRole string
//go:embed testfiles/organization-role.tf
var organizationRole string

//go:embed testfiles/custom-role.tf
var customRole string

var testConfigVars = config.Variables{
"project_id": config.StringVariable(testutil.ProjectId),
"test_service_account": config.StringVariable(testutil.TestProjectServiceAccountEmail),
"organization_id": config.StringVariable(testutil.OrganizationId),
}

var testConfigVarsCustomRole = config.Variables{
"project_id": config.StringVariable(testutil.ProjectId),
"test_service_account": config.StringVariable(testutil.TestProjectServiceAccountEmail),
"organization_id": config.StringVariable(testutil.OrganizationId),
"role_name": config.StringVariable(fmt.Sprintf("tf-acc-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlpha))),
"role_description": config.StringVariable("Some description"),
"role_permissions_0": config.StringVariable("iam.role.list"),
}

var testConfigVarsCustomRoleUpdated = config.Variables{
"project_id": config.StringVariable(testutil.ProjectId),
"test_service_account": config.StringVariable(testutil.TestProjectServiceAccountEmail),
"organization_id": config.StringVariable(testutil.OrganizationId),
"role_name": config.StringVariable(fmt.Sprintf("tf-acc-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlpha))),
"role_description": config.StringVariable("Updated description"),
"role_permissions_0": config.StringVariable("iam.role.edit"),
}

func TestAccProjectRoleAssignmentResource(t *testing.T) {
t.Log(testutil.AuthorizationProviderConfig())
resource.Test(t, resource.TestCase{
Expand All @@ -53,8 +75,7 @@ func TestAccProjectRoleAssignmentResource(t *testing.T) {
return err
}

members, err := client.ListMembers(context.TODO(), "project", testutil.ProjectId).Execute()

members, err := client.ListMembers(context.Background(), "project", testutil.ProjectId).Execute()
if err != nil {
return err
}
Expand Down Expand Up @@ -93,18 +114,105 @@ func TestAccProjectRoleAssignmentResource(t *testing.T) {
},
},
})

resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
ConfigVariables: testConfigVarsCustomRole,
Config: testutil.AuthorizationProviderConfig() + customRole,
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("stackit_authorization_project_custom_role.custom-role", "resource_id", testutil.ConvertConfigVariable(testConfigVarsCustomRole["project_id"])),
resource.TestCheckResourceAttr("stackit_authorization_project_custom_role.custom-role", "name", testutil.ConvertConfigVariable(testConfigVarsCustomRole["role_name"])),
resource.TestCheckResourceAttr("stackit_authorization_project_custom_role.custom-role", "description", testutil.ConvertConfigVariable(testConfigVarsCustomRole["role_description"])),
resource.TestCheckResourceAttr("stackit_authorization_project_custom_role.custom-role", "permissions.#", "1"),
resource.TestCheckTypeSetElemAttr("stackit_authorization_project_custom_role.custom-role", "permissions.*", testutil.ConvertConfigVariable(testConfigVarsCustomRole["role_permissions_0"])),
resource.TestCheckResourceAttrSet("stackit_authorization_project_custom_role.custom-role", "role_id"),
),
},
// Data source
{
ConfigVariables: testConfigVarsCustomRole,
Config: fmt.Sprintf(`
%s

data "stackit_authorization_project_custom_role" "custom-role" {
resource_id = stackit_authorization_project_custom_role.custom-role.resource_id
role_id = stackit_authorization_project_custom_role.custom-role.role_id
}
`,
testutil.AuthorizationProviderConfig()+customRole,
),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("data.stackit_authorization_project_custom_role.custom-role", "resource_id", testutil.ConvertConfigVariable(testConfigVarsCustomRole["project_id"])),
resource.TestCheckResourceAttrPair(
"stackit_authorization_project_custom_role.custom-role", "resource_id",
"data.stackit_authorization_project_custom_role.custom-role", "resource_id",
),
resource.TestCheckResourceAttrPair(
"stackit_authorization_project_custom_role.custom-role", "role_id",
"data.stackit_authorization_project_custom_role.custom-role", "role_id",
),
resource.TestCheckResourceAttrPair(
"stackit_authorization_project_custom_role.custom-role", "name",
"data.stackit_authorization_project_custom_role.custom-role", "name",
),
resource.TestCheckResourceAttrPair(
"stackit_authorization_project_custom_role.custom-role", "description",
"data.stackit_authorization_project_custom_role.custom-role", "description",
),
resource.TestCheckResourceAttrPair(
"stackit_authorization_project_custom_role.custom-role", "permissions",
"data.stackit_authorization_project_custom_role.custom-role", "permissions",
),
),
},
// Import
{
ConfigVariables: testConfigVarsCustomRole,
ResourceName: "stackit_authorization_project_custom_role.custom-role",
ImportStateIdFunc: func(s *terraform.State) (string, error) {
r, ok := s.RootModule().Resources["stackit_authorization_project_custom_role.custom-role"]
if !ok {
return "", fmt.Errorf("couldn't find resource stackit_authorization_project_custom_role.custom-role")
}
roleId, ok := r.Primary.Attributes["role_id"]
if !ok {
return "", fmt.Errorf("couldn't find attribute role_id")
}

return fmt.Sprintf("%s,%s", testutil.ProjectId, roleId), nil
},
ImportState: true,
ImportStateVerify: true,
},
// Update
{
ConfigVariables: testConfigVarsCustomRoleUpdated,
Config: testutil.AuthorizationProviderConfig() + customRole,
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("stackit_authorization_project_custom_role.custom-role", "resource_id", testutil.ConvertConfigVariable(testConfigVarsCustomRoleUpdated["project_id"])),
resource.TestCheckResourceAttr("stackit_authorization_project_custom_role.custom-role", "name", testutil.ConvertConfigVariable(testConfigVarsCustomRoleUpdated["role_name"])),
resource.TestCheckResourceAttr("stackit_authorization_project_custom_role.custom-role", "description", testutil.ConvertConfigVariable(testConfigVarsCustomRoleUpdated["role_description"])),
resource.TestCheckResourceAttr("stackit_authorization_project_custom_role.custom-role", "permissions.#", "1"),
resource.TestCheckTypeSetElemAttr("stackit_authorization_project_custom_role.custom-role", "permissions.*", testutil.ConvertConfigVariable(testConfigVarsCustomRoleUpdated["role_permissions_0"])),
resource.TestCheckResourceAttrSet("stackit_authorization_project_custom_role.custom-role", "role_id"),
),
},
// Deletion is done by the framework implicitly
},
})
}

func authApiClient() (*authorization.APIClient, error) {
var client *authorization.APIClient
var err error
if testutil.AuthorizationCustomEndpoint == "" {
client, err = authorization.NewAPIClient(
stackitSdkConfig.WithRegion("eu01"),
)
if testutil.AuthorizationCustomEndpoint == "" || testutil.TokenCustomEndpoint == "" {
client, err = authorization.NewAPIClient()
} else {
client, err = authorization.NewAPIClient(
stackitSdkConfig.WithEndpoint(testutil.AuthorizationCustomEndpoint),
stackitSdkConfig.WithTokenEndpoint(testutil.TokenCustomEndpoint),
)
}
if err != nil {
Expand Down
158 changes: 158 additions & 0 deletions stackit/internal/services/authorization/customrole/datasource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package customrole

import (
"context"
"errors"
"fmt"
"net/http"

"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
"github.com/stackitcloud/stackit-sdk-go/services/authorization"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
authorizationUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/authorization/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)

// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &customRoleDataSource{}
)

// NewAuthorizationDataSource creates a new customrole of the authorizationDataSource.
func NewCustomRoleDataSource() datasource.DataSource {
return &customRoleDataSource{}
}

// NewProjectRoleAssignmentDataSources is a helper function generate custom role
// data sources for all possible resource types.
func NewCustomRoleDataSources() []func() datasource.DataSource {
resources := make([]func() datasource.DataSource, 0)
for _, v := range resourceTypes {
resources = append(resources, func() datasource.DataSource {
return &customRoleDataSource{
resourceType: v,
}
})
}

return resources
}

// customRoleDataSource is the datasource implementation.
type customRoleDataSource struct {
resourceType string
client *authorization.APIClient
}

// Configure sets up the API client for the authorization customrole resource.
func (d *customRoleDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}

if resp.Diagnostics.HasError() {
return
}

apiClient := authorizationUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)

if resp.Diagnostics.HasError() {
return
}

d.client = apiClient

tflog.Info(ctx, "authorization client configured")
}

// Metadata provides metadata for the custom role datasource.
func (d *customRoleDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = fmt.Sprintf("%s_authorization_%s_custom_role", req.ProviderTypeName, d.resourceType)
}

// Schema defines the schema for the custom role data source.
func (d *customRoleDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: descriptions["id"],
Computed: true,
},
"role_id": schema.StringAttribute{
Description: descriptions["role_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"resource_id": schema.StringAttribute{
Description: descriptions["resource_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"name": schema.StringAttribute{
Description: descriptions["name"],
Computed: true,
},
"description": schema.StringAttribute{
Description: descriptions["subject"],
Computed: true,
},
"permissions": schema.ListAttribute{
ElementType: types.StringType,
Description: descriptions["permissions"],
Computed: true,
},
},
}
}

func (d *customRoleDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { //nolint:gocritic // function signature required by Terraform
var model Model
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

resourceId := model.ResourceId.ValueString()
roleId := model.RoleId.ValueString()

roleResp, err := d.client.GetRole(ctx, d.resourceType, resourceId, roleId).Execute()
if err != nil {
var oapiErr *oapierror.GenericOpenAPIError

ok := errors.As(err, &oapiErr)
if ok && oapiErr.StatusCode == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}

core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading custom role", fmt.Sprintf("Calling API: %v", err))

return
}

if err = mapGetCustomRoleResponse(ctx, roleResp, &model); err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading custom role", fmt.Sprintf("Processing API response: %v", err))
return
}

// Set the updated state.
diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...)
tflog.Info(ctx, fmt.Sprintf("read custom role %s", roleId))
}
Loading