Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ovh_cloud_project_user_s3_policy: Read policy field from API #707

Merged
merged 1 commit into from
Aug 20, 2024
Merged
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
36 changes: 36 additions & 0 deletions ovh/helpers/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package helpers

import (
"bytes"
"encoding/json"
"reflect"
)

// Copied from https://github.com/hashicorp/terraform-provider-aws/blob/main/internal/verify/json.go
func JSONStringsEqual(s1, s2 string) bool {
b1 := bytes.NewBufferString("")
if err := json.Compact(b1, []byte(s1)); err != nil {
return false
}

b2 := bytes.NewBufferString("")
if err := json.Compact(b2, []byte(s2)); err != nil {
return false
}

return JSONBytesEqual(b1.Bytes(), b2.Bytes())
}

func JSONBytesEqual(b1, b2 []byte) bool {
var o1 interface{}
if err := json.Unmarshal(b1, &o1); err != nil {
return false
}

var o2 interface{}
if err := json.Unmarshal(b2, &o2); err != nil {
return false
}

return reflect.DeepEqual(o1, o2)
}
6 changes: 5 additions & 1 deletion ovh/resource_cloud_project_user_s3_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ func resourceCloudProjectUserS3Policy() *schema.Resource {
Type: schema.TypeString,
Required: true,
Description: "The policy document. This is a JSON formatted string.",
DiffSuppressFunc: func(key, old, new string, d *schema.ResourceData) bool {
return helpers.JSONStringsEqual(old, new)
},
},
},
}
Expand All @@ -63,7 +66,7 @@ func resourceCloudProjectUserS3PolicyImportState(ctx context.Context, d *schema.
}

if serviceName == "" || userId == "" {
return nil, fmt.Errorf("Import ID is not service_name/user_id formatted. Got %s", d.Id())
return nil, fmt.Errorf("import ID is not service_name/user_id formatted. Got %s", d.Id())
}

d.SetId(buildUserS3PolicyId(serviceName, userId))
Expand Down Expand Up @@ -106,6 +109,7 @@ func resourceCloudProjectUserS3PolicyRead(ctx context.Context, d *schema.Resourc
}

d.SetId(buildUserS3PolicyId(serviceName, userId))
d.Set("policy", s3Policy.Policy)

log.Printf("[DEBUG] Policy %s set for user %s", s3Policy.Policy, userId)
return nil
Expand Down
76 changes: 60 additions & 16 deletions ovh/resource_cloud_project_user_s3_policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/plancheck"
"github.com/ovh/terraform-provider-ovh/ovh/helpers"
)

const testAccCloudProjectUserS3PolicyConfig_basic = `
Expand All @@ -32,37 +34,79 @@ EOF
}
`

const policyRWBucket = `{
"Statement":[{
"Sid": "RWContainer",
"Effect": "Allow",
"Action":["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket", "s3:ListMultipartUploadParts", "s3:ListBucketMultipartUploads", "s3:AbortMultipartUpload", "s3:GetBucketLocation"],
"Resource":["arn:aws:s3:::hp-bucket", "arn:aws:s3:::hp-bucket/*"]
}]
}`
const (
policyRWBucket = `{
"Statement":[{
"Sid": "RWContainer",
"Effect": "Allow",
"Action":["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket", "s3:ListMultipartUploadParts", "s3:ListBucketMultipartUploads", "s3:AbortMultipartUpload", "s3:GetBucketLocation"],
"Resource":["arn:aws:s3:::hp-bucket", "arn:aws:s3:::hp-bucket/*"]
}]
}`

policyRWBucketNoUpdate = `{
"Statement":[{
"Sid": "RWContainer",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket", "s3:ListMultipartUploadParts", "s3:ListBucketMultipartUploads", "s3:AbortMultipartUpload", "s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::hp-bucket", "arn:aws:s3:::hp-bucket/*"]
}]
}`

policyRWBucketUpdated = `{
"Statement":[{
"Sid": "RWContainer",
"Effect": "Deny",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::hp-bucket/*"]
}]
}`
)

func TestAccCloudProjectUserS3Policy_basic(t *testing.T) {
serviceName := os.Getenv("OVH_CLOUD_PROJECT_SERVICE_TEST")

config := fmt.Sprintf(testAccCloudProjectUserS3PolicyConfig_basic, serviceName, policyRWBucket)
resourceName := "ovh_cloud_project_user_s3_policy.s3_policy"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheckCloud(t); testAccCheckCloudProjectExists(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Config: fmt.Sprintf(testAccCloudProjectUserS3PolicyConfig_basic, serviceName, policyRWBucket),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet(resourceName, "policy"),
resource.TestCheckResourceAttr(resourceName, "policy", fmt.Sprintf("%s\n", policyRWBucket)),
resource.TestCheckResourceAttrWith(resourceName, "policy", func(value string) error {
if !helpers.JSONStringsEqual(value, policyRWBucket) {
return fmt.Errorf("policies are not equal, expected %q, got %q", value, policyRWBucket)
}
return nil
}),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"policy"},
Config: fmt.Sprintf(testAccCloudProjectUserS3PolicyConfig_basic, serviceName, policyRWBucketNoUpdate),
ConfigPlanChecks: resource.ConfigPlanChecks{
PreApply: []plancheck.PlanCheck{
ExpectEmptyPlan(),
},
},
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: fmt.Sprintf(testAccCloudProjectUserS3PolicyConfig_basic, serviceName, policyRWBucketUpdated),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet(resourceName, "policy"),
resource.TestCheckResourceAttrWith(resourceName, "policy", func(value string) error {
if !helpers.JSONStringsEqual(value, policyRWBucketUpdated) {
return fmt.Errorf("policies are not equal, expected %q, got %q", value, policyRWBucketUpdated)
}
return nil
}),
),
},
},
})
Expand Down
29 changes: 29 additions & 0 deletions ovh/testing.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
package ovh

import (
"context"
"errors"
"fmt"

"github.com/hashicorp/terraform-plugin-testing/plancheck"
)

const (
test_prefix = "testacc-terraform"
)

// Custom type used to check that a plan is empty in acceptance tests
var _ plancheck.PlanCheck = expectEmptyPlan{}

type expectEmptyPlan struct{}

func (e expectEmptyPlan) CheckPlan(ctx context.Context, req plancheck.CheckPlanRequest, resp *plancheck.CheckPlanResponse) {
var result error

for _, rc := range req.Plan.ResourceChanges {
if !rc.Change.Actions.NoOp() {
result = errors.Join(result, fmt.Errorf("expected empty plan, but %s has planned action(s): %v", rc.Address, rc.Change.Actions))
}
}

resp.Error = result
}

func ExpectEmptyPlan() plancheck.PlanCheck {
return expectEmptyPlan{}
}