diff --git a/.changelog/6493.txt b/.changelog/6493.txt new file mode 100644 index 0000000000..801c08eb73 --- /dev/null +++ b/.changelog/6493.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +Enable IAM resources for Security Command Center sources +``` diff --git a/google/iam_scc_source.go b/google/iam_scc_source.go new file mode 100644 index 0000000000..1729e63adb --- /dev/null +++ b/google/iam_scc_source.go @@ -0,0 +1,182 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "google.golang.org/api/cloudresourcemanager/v1" +) + +var SecurityCenterSourceIamSchema = map[string]*schema.Schema{ + "organization": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "source": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + }, +} + +type SecurityCenterSourceIamUpdater struct { + organization string + source string + d TerraformResourceData + Config *Config +} + +func SecurityCenterSourceIamUpdaterProducer(d TerraformResourceData, config *Config) (ResourceIamUpdater, error) { + values := make(map[string]string) + + if v, ok := d.GetOk("organization"); ok { + values["organization"] = v.(string) + } + + if v, ok := d.GetOk("source"); ok { + values["source"] = v.(string) + } + + // We may have gotten either a long or short name, so attempt to parse long name if possible + m, err := getImportIdQualifiers([]string{"organizations/(?P[^/]+)/sources/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Get("source").(string)) + if err != nil { + return nil, err + } + + for k, v := range m { + values[k] = v + } + + u := &SecurityCenterSourceIamUpdater{ + organization: values["organization"], + source: values["source"], + d: d, + Config: config, + } + + if err := d.Set("organization", u.organization); err != nil { + return nil, fmt.Errorf("Error setting organization: %s", err) + } + if err := d.Set("source", u.GetResourceId()); err != nil { + return nil, fmt.Errorf("Error setting source: %s", err) + } + + return u, nil +} + +func SecurityCenterSourceIdParseFunc(d *schema.ResourceData, config *Config) error { + values := make(map[string]string) + + m, err := getImportIdQualifiers([]string{"organizations/(?P[^/]+)/sources/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Id()) + if err != nil { + return err + } + + for k, v := range m { + values[k] = v + } + + u := &SecurityCenterSourceIamUpdater{ + organization: values["organization"], + source: values["source"], + d: d, + Config: config, + } + if err := d.Set("source", u.GetResourceId()); err != nil { + return fmt.Errorf("Error setting source: %s", err) + } + d.SetId(u.GetResourceId()) + return nil +} + +func (u *SecurityCenterSourceIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { + url, err := u.qualifySourceUrl("getIamPolicy") + if err != nil { + return nil, err + } + + var obj map[string]interface{} + + userAgent, err := generateUserAgentString(u.d, u.Config.userAgent) + if err != nil { + return nil, err + } + + policy, err := sendRequest(u.Config, "POST", "", url, userAgent, obj) + if err != nil { + return nil, errwrap.Wrapf(fmt.Sprintf("Error retrieving IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + out := &cloudresourcemanager.Policy{} + err = Convert(policy, out) + if err != nil { + return nil, errwrap.Wrapf("Cannot convert a policy to a resource manager policy: {{err}}", err) + } + + return out, nil +} + +func (u *SecurityCenterSourceIamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error { + json, err := ConvertToMap(policy) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + obj["policy"] = json + + url, err := u.qualifySourceUrl("setIamPolicy") + if err != nil { + return err + } + + userAgent, err := generateUserAgentString(u.d, u.Config.userAgent) + if err != nil { + return err + } + + _, err = sendRequestWithTimeout(u.Config, "POST", "", url, userAgent, obj, u.d.Timeout(schema.TimeoutCreate)) + if err != nil { + return errwrap.Wrapf(fmt.Sprintf("Error setting IAM policy for %s: {{err}}", u.DescribeResource()), err) + } + + return nil +} + +func (u *SecurityCenterSourceIamUpdater) qualifySourceUrl(methodIdentifier string) (string, error) { + urlTemplate := fmt.Sprintf("{{SecurityCenterBasePath}}%s:%s", fmt.Sprintf("organizations/%s/sources/%s", u.organization, u.source), methodIdentifier) + url, err := replaceVars(u.d, u.Config, urlTemplate) + if err != nil { + return "", err + } + return url, nil +} + +func (u *SecurityCenterSourceIamUpdater) GetResourceId() string { + return fmt.Sprintf("organizations/%s/sources/%s", u.organization, u.source) +} + +func (u *SecurityCenterSourceIamUpdater) GetMutexKey() string { + return fmt.Sprintf("iam-securitycenter-source-%s", u.GetResourceId()) +} + +func (u *SecurityCenterSourceIamUpdater) DescribeResource() string { + return fmt.Sprintf("securitycenter source %q", u.GetResourceId()) +} diff --git a/google/iam_scc_source_test.go b/google/iam_scc_source_test.go new file mode 100644 index 0000000000..8afb6bc335 --- /dev/null +++ b/google/iam_scc_source_test.go @@ -0,0 +1,219 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccSecurityCenterSourceIamBinding(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/securitycenter.sourcesViewer", + "org_id": getTestOrgFromEnv(t), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccSecurityCenterSourceIamBinding_basic(context), + }, + { + ResourceName: "google_scc_source_iam_binding.foo", + ImportStateIdFunc: func(state *terraform.State) (string, error) { + // This has to be a function because sources only use numeric IDs + id := state.RootModule().Resources["google_scc_source.custom_source"].Primary.Attributes["id"] + return fmt.Sprintf("%s %s", + id, + context["role"], + ), nil + }, + ImportState: true, + ImportStateVerify: true, + }, + { + // Test Iam Binding update + Config: testAccSecurityCenterSourceIamBinding_update(context), + }, + { + ResourceName: "google_scc_source_iam_binding.foo", + ImportStateIdFunc: func(state *terraform.State) (string, error) { + // This has to be a function because sources only use numeric IDs + id := state.RootModule().Resources["google_scc_source.custom_source"].Primary.Attributes["id"] + return fmt.Sprintf("%s %s", + id, + context["role"], + ), nil + }, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccSecurityCenterSourceIamMember(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/securitycenter.sourcesViewer", + "org_id": getTestOrgFromEnv(t), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + // Test Iam Member creation (no update for member, no need to test) + Config: testAccSecurityCenterSourceIamMember_basic(context), + }, + { + ResourceName: "google_scc_source_iam_member.foo", + ImportStateIdFunc: func(state *terraform.State) (string, error) { + // This has to be a function because sources only use numeric IDs + id := state.RootModule().Resources["google_scc_source.custom_source"].Primary.Attributes["id"] + return fmt.Sprintf("%s %s user:admin@hashicorptest.com", + id, + context["role"], + ), nil + }, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccSecurityCenterSourceIamPolicy(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + "role": "roles/securitycenter.sourcesViewer", + "org_id": getTestOrgFromEnv(t), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccSecurityCenterSourceIamPolicy_basic(context), + }, + { + ResourceName: "google_scc_source_iam_policy.foo", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccSecurityCenterSourceIamPolicy_emptyBinding(context), + }, + { + ResourceName: "google_scc_source_iam_policy.foo", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccSecurityCenterSourceIamMember_basic(context map[string]interface{}) string { + return Nprintf(` +resource "google_scc_source" "custom_source" { + display_name = "tf-test-source%{random_suffix}" + organization = "%{org_id}" + description = "My custom Cloud Security Command Center Finding Source" +} + +resource "google_scc_source_iam_member" "foo" { + source = google_scc_source.custom_source.id + organization = "%{org_id}" + role = "%{role}" + member = "user:admin@hashicorptest.com" +} +`, context) +} + +func testAccSecurityCenterSourceIamPolicy_basic(context map[string]interface{}) string { + return Nprintf(` +resource "google_scc_source" "custom_source" { + display_name = "tf-test-source%{random_suffix}" + organization = "%{org_id}" + description = "My custom Cloud Security Command Center Finding Source" +} + +data "google_iam_policy" "foo" { + binding { + role = "%{role}" + members = ["user:admin@hashicorptest.com"] + } +} + +resource "google_scc_source_iam_policy" "foo" { + source = google_scc_source.custom_source.id + organization = "%{org_id}" + policy_data = data.google_iam_policy.foo.policy_data +} +`, context) +} + +func testAccSecurityCenterSourceIamPolicy_emptyBinding(context map[string]interface{}) string { + return Nprintf(` +resource "google_scc_source" "custom_source" { + display_name = "tf-test-source%{random_suffix}" + organization = "%{org_id}" + description = "My custom Cloud Security Command Center Finding Source" +} + +data "google_iam_policy" "foo" { +} + +resource "google_scc_source_iam_policy" "foo" { + source = google_scc_source.custom_source.id + organization = "%{org_id}" + policy_data = data.google_iam_policy.foo.policy_data +} +`, context) +} + +func testAccSecurityCenterSourceIamBinding_basic(context map[string]interface{}) string { + return Nprintf(` +resource "google_scc_source" "custom_source" { + display_name = "tf-test-source%{random_suffix}" + organization = "%{org_id}" + description = "My custom Cloud Security Command Center Finding Source" +} + +resource "google_scc_source_iam_binding" "foo" { + source = google_scc_source.custom_source.id + organization = "%{org_id}" + role = "%{role}" + members = ["user:admin@hashicorptest.com"] +} +`, context) +} + +func testAccSecurityCenterSourceIamBinding_update(context map[string]interface{}) string { + return Nprintf(` +resource "google_scc_source" "custom_source" { + display_name = "tf-test-source%{random_suffix}" + organization = "%{org_id}" + description = "My custom Cloud Security Command Center Finding Source" +} + +resource "google_scc_source_iam_binding" "foo" { + source = google_scc_source.custom_source.id + organization = "%{org_id}" + role = "%{role}" + members = ["user:admin@hashicorptest.com", "user:gterraformtest1@gmail.com"] +} +`, context) +} diff --git a/google/provider.go b/google/provider.go index 7766266375..0c89f8a2ca 100644 --- a/google/provider.go +++ b/google/provider.go @@ -902,8 +902,8 @@ func Provider() *schema.Provider { } // Generated resources: 240 -// Generated IAM resources: 138 -// Total generated resources: 378 +// Generated IAM resources: 141 +// Total generated resources: 381 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -1243,6 +1243,9 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_secret_manager_secret_iam_policy": ResourceIamPolicy(SecretManagerSecretIamSchema, SecretManagerSecretIamUpdaterProducer, SecretManagerSecretIdParseFunc), "google_secret_manager_secret_version": resourceSecretManagerSecretVersion(), "google_scc_source": resourceSecurityCenterSource(), + "google_scc_source_iam_binding": ResourceIamBinding(SecurityCenterSourceIamSchema, SecurityCenterSourceIamUpdaterProducer, SecurityCenterSourceIdParseFunc), + "google_scc_source_iam_member": ResourceIamMember(SecurityCenterSourceIamSchema, SecurityCenterSourceIamUpdaterProducer, SecurityCenterSourceIdParseFunc), + "google_scc_source_iam_policy": ResourceIamPolicy(SecurityCenterSourceIamSchema, SecurityCenterSourceIamUpdaterProducer, SecurityCenterSourceIdParseFunc), "google_scc_notification_config": resourceSecurityCenterNotificationConfig(), "google_endpoints_service_iam_binding": ResourceIamBinding(ServiceManagementServiceIamSchema, ServiceManagementServiceIamUpdaterProducer, ServiceManagementServiceIdParseFunc), "google_endpoints_service_iam_member": ResourceIamMember(ServiceManagementServiceIamSchema, ServiceManagementServiceIamUpdaterProducer, ServiceManagementServiceIdParseFunc), diff --git a/website/docs/r/scc_source.html.markdown b/website/docs/r/scc_source.html.markdown index d5704cdbe2..0604fd2ab4 100644 --- a/website/docs/r/scc_source.html.markdown +++ b/website/docs/r/scc_source.html.markdown @@ -28,7 +28,7 @@ monitor, etc. To get more information about Source, see: -* [API documentation](https://cloud.google.com/security-command-center/docs/reference/rest/v1beta1/organizations.sources) +* [API documentation](https://cloud.google.com/security-command-center/docs/reference/rest/v1/organizations.sources) * How-to Guides * [Official Documentation](https://cloud.google.com/security-command-center/docs) diff --git a/website/docs/r/scc_source_iam.html.markdown b/website/docs/r/scc_source_iam.html.markdown new file mode 100644 index 0000000000..218e8a7ee4 --- /dev/null +++ b/website/docs/r/scc_source_iam.html.markdown @@ -0,0 +1,135 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** Type: MMv1 *** +# +# ---------------------------------------------------------------------------- +# +# This file is automatically generated by Magic Modules and manual +# changes will be clobbered when the file is regenerated. +# +# Please read more about how to change this file in +# .github/CONTRIBUTING.md. +# +# ---------------------------------------------------------------------------- +subcategory: "Security Command Center (SCC)" +page_title: "Google: google_scc_source_iam" +description: |- + Collection of resources to manage IAM policy for Security Command Center (SCC) Source +--- + +# IAM policy for Security Command Center (SCC) Source +Three different resources help you manage your IAM policy for Security Command Center (SCC) Source. Each of these resources serves a different use case: + +* `google_scc_source_iam_policy`: Authoritative. Sets the IAM policy for the source and replaces any existing policy already attached. +* `google_scc_source_iam_binding`: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other roles within the IAM policy for the source are preserved. +* `google_scc_source_iam_member`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the source are preserved. + +~> **Note:** `google_scc_source_iam_policy` **cannot** be used in conjunction with `google_scc_source_iam_binding` and `google_scc_source_iam_member` or they will fight over what your policy should be. + +~> **Note:** `google_scc_source_iam_binding` resources **can be** used in conjunction with `google_scc_source_iam_member` resources **only if** they do not grant privilege to the same role. + + + + +## google\_scc\_source\_iam\_policy + +```hcl +data "google_iam_policy" "admin" { + binding { + role = "roles/viewer" + members = [ + "user:jane@example.com", + ] + } +} + +resource "google_scc_source_iam_policy" "policy" { + source = google_scc_source.custom_source.name + policy_data = data.google_iam_policy.admin.policy_data +} +``` + +## google\_scc\_source\_iam\_binding + +```hcl +resource "google_scc_source_iam_binding" "binding" { + source = google_scc_source.custom_source.name + role = "roles/viewer" + members = [ + "user:jane@example.com", + ] +} +``` + +## google\_scc\_source\_iam\_member + +```hcl +resource "google_scc_source_iam_member" "member" { + source = google_scc_source.custom_source.name + role = "roles/viewer" + member = "user:jane@example.com" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `source` - (Required) Used to find the parent resource to bind the IAM policy to + +* `member/members` - (Required) Identities that will be granted the privilege in `role`. + Each entry can have one of the following values: + * **allUsers**: A special identifier that represents anyone who is on the internet; with or without a Google account. + * **allAuthenticatedUsers**: A special identifier that represents anyone who is authenticated with a Google account or a service account. + * **user:{emailid}**: An email address that represents a specific Google account. For example, alice@gmail.com or joe@example.com. + * **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com. + * **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com. + * **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com. + * **projectOwner:projectid**: Owners of the given project. For example, "projectOwner:my-example-project" + * **projectEditor:projectid**: Editors of the given project. For example, "projectEditor:my-example-project" + * **projectViewer:projectid**: Viewers of the given project. For example, "projectViewer:my-example-project" + +* `role` - (Required) The role that should be applied. Only one + `google_scc_source_iam_binding` can be used per role. Note that custom roles must be of the format + `[projects|organizations]/{parent-name}/roles/{role-name}`. + +* `policy_data` - (Required only by `google_scc_source_iam_policy`) The policy data generated by + a `google_iam_policy` data source. + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are +exported: + +* `etag` - (Computed) The etag of the IAM policy. + +## Import + +For all import syntaxes, the "resource in question" can take any of the following forms: + +* organizations/{{organization}}/sources/{{source}} +* {{organization}}/{{source}} +* {{source}} + +Any variables not passed in the import command will be taken from the provider configuration. + +Security Command Center (SCC) source IAM resources can be imported using the resource identifiers, role, and member. + +IAM member imports use space-delimited identifiers: the resource in question, the role, and the member identity, e.g. +``` +$ terraform import google_scc_source_iam_member.editor "organizations/{{organization}}/sources/{{source}} roles/viewer user:jane@example.com" +``` + +IAM binding imports use space-delimited identifiers: the resource in question and the role, e.g. +``` +$ terraform import google_scc_source_iam_binding.editor "organizations/{{organization}}/sources/{{source}} roles/viewer" +``` + +IAM policy imports use the identifier of the resource in question, e.g. +``` +$ terraform import google_scc_source_iam_policy.editor organizations/{{organization}}/sources/{{source}} +``` + +-> **Custom Roles**: If you're importing a IAM resource with a custom role, make sure to use the + full name of the custom role, e.g. `[projects/my-project|organizations/my-org]/roles/my-custom-role`.