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
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/stackitcloud/terraform-provider-stackit
go 1.24.0

require (
dev.azure.com/schwarzit/schwarzit.stackit-public/stackit-sdk-go-internal.git/services/authorization v0.0.0-20251126130857-9f2211a4c524
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

internal SDK modules shouldn't be used

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I forgot to remove it after testing...

github.com/google/go-cmp v0.7.0
github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=
dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
dev.azure.com/schwarzit/schwarzit.stackit-public/stackit-sdk-go-internal.git/services/authorization v0.0.0-20251126130857-9f2211a4c524 h1:ITrpsUZNlZSMWF5W7Jixp5ekWxiMgy4KOURODk73uhI=
dev.azure.com/schwarzit/schwarzit.stackit-public/stackit-sdk-go-internal.git/services/authorization v0.0.0-20251126130857-9f2211a4c524/go.mod h1:ZupN/2xICyLvD0FPxihbUH2KNXtVBVpp/DzsoyFKib4=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/ProtonMail/go-crypto v1.1.6 h1:ZcV+Ropw6Qn0AX9brlQLAUXfqLBc7Bl+f/DmNxpLfdw=
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
Loading