From 75b5a1cf04e707f50af4d7ece64ca5e01c1b204a Mon Sep 17 00:00:00 2001 From: Matthias Theuermann <73223147+mati007thm@users.noreply.github.com> Date: Fri, 13 Dec 2024 05:59:26 +0100 Subject: [PATCH] Jira integration (#168) fixes https://github.com/mondoohq/terraform-provider-mondoo/issues/160 --------- Signed-off-by: Matthias Theuermann --- .github/actions/spelling/expect.txt | 1 + docs/resources/integration_jira.md | 68 ++++ .../resources/mondoo_integration_jira/main.tf | 8 + .../mondoo_integration_jira/resource.tf | 24 ++ internal/provider/gql.go | 9 + .../provider/integration_jira_resource.go | 295 ++++++++++++++++++ .../integration_jira_resource_test.go | 103 ++++++ internal/provider/provider.go | 1 + 8 files changed, 509 insertions(+) create mode 100644 docs/resources/integration_jira.md create mode 100644 examples/resources/mondoo_integration_jira/main.tf create mode 100644 examples/resources/mondoo_integration_jira/resource.tf create mode 100644 internal/provider/integration_jira_resource.go create mode 100644 internal/provider/integration_jira_resource_test.go diff --git a/.github/actions/spelling/expect.txt b/.github/actions/spelling/expect.txt index e182c6c..7c88240 100644 --- a/.github/actions/spelling/expect.txt +++ b/.github/actions/spelling/expect.txt @@ -15,6 +15,7 @@ Hmj JFB JFUz Jhb +jira KBp ljq LQV diff --git a/docs/resources/integration_jira.md b/docs/resources/integration_jira.md new file mode 100644 index 0000000..a6f0f17 --- /dev/null +++ b/docs/resources/integration_jira.md @@ -0,0 +1,68 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "mondoo_integration_jira Resource - terraform-provider-mondoo" +subcategory: "" +description: |- + Integrate the Ticketing System Jira with Mondoo to automatically create and close issues based on Mondoo findings. +--- + +# mondoo_integration_jira (Resource) + +Integrate the Ticketing System Jira with Mondoo to automatically create and close issues based on Mondoo findings. + +## Example Usage + +```terraform +variable "jira_token" { + description = "The Jira API Token" + type = string + sensitive = true +} + +provider "mondoo" { + space = "hungry-poet-123456" +} + +# Setup the Jira integration +resource "mondoo_integration_jira" "jira_integration" { + name = "My Jira Integration" + host = "https://your-instance.atlassian.net" + email = "jira.owner@email.com" + # default_project = "MONDOO" + + auto_create = true + auto_close = true + + credentials = { + token = var.jira_token + } +} +``` + + +## Schema + +### Required + +- `credentials` (Attributes) (see [below for nested schema](#nestedatt--credentials)) +- `email` (String) Jira user email. +- `host` (String) Jira host URL. +- `name` (String) Name of the integration. + +### Optional + +- `auto_close` (Boolean) Automatically close Jira issues for resolved Mondoo findings +- `auto_create` (Boolean) Automatically create Jira issues for Mondoo findings. +- `default_project` (String) Default Jira project (is represented by the project key e.g. `MONDOO`). +- `space_id` (String) Mondoo Space Identifier. If it is not provided, the provider space is used. + +### Read-Only + +- `mrn` (String) Integration identifier. + + +### Nested Schema for `credentials` + +Required: + +- `token` (String, Sensitive) Jira API token. diff --git a/examples/resources/mondoo_integration_jira/main.tf b/examples/resources/mondoo_integration_jira/main.tf new file mode 100644 index 0000000..24d24a1 --- /dev/null +++ b/examples/resources/mondoo_integration_jira/main.tf @@ -0,0 +1,8 @@ +terraform { + required_providers { + mondoo = { + source = "mondoohq/mondoo" + version = ">= 0.19" + } + } +} \ No newline at end of file diff --git a/examples/resources/mondoo_integration_jira/resource.tf b/examples/resources/mondoo_integration_jira/resource.tf new file mode 100644 index 0000000..de60f4e --- /dev/null +++ b/examples/resources/mondoo_integration_jira/resource.tf @@ -0,0 +1,24 @@ +variable "jira_token" { + description = "The Jira API Token" + type = string + sensitive = true +} + +provider "mondoo" { + space = "hungry-poet-123456" +} + +# Setup the Jira integration +resource "mondoo_integration_jira" "jira_integration" { + name = "My Jira Integration" + host = "https://your-instance.atlassian.net" + email = "jira.owner@email.com" + # default_project = "MONDOO" + + auto_create = true + auto_close = true + + credentials = { + token = var.jira_token + } +} diff --git a/internal/provider/gql.go b/internal/provider/gql.go index 3f5f840..4454e72 100644 --- a/internal/provider/gql.go +++ b/internal/provider/gql.go @@ -617,6 +617,14 @@ type ShodanConfigurationOptions struct { Targets []string } +type JiraConfigurationOptions struct { + Host string + Email string + DefaultProject string + AutoCloseTickets bool + AutoCreateCases bool +} + type EmailConfigurationOptions struct { Recipients []EmailRecipient AutoCreateTickets bool @@ -639,6 +647,7 @@ type ClientIntegrationConfigurationOptions struct { GithubConfigurationOptions GithubConfigurationOptions `graphql:"... on GithubConfigurationOptions"` HostedAwsConfigurationOptions HostedAwsConfigurationOptions `graphql:"... on HostedAwsConfigurationOptions"` ShodanConfigurationOptions ShodanConfigurationOptions `graphql:"... on ShodanConfigurationOptions"` + JiraConfigurationOptions JiraConfigurationOptions `graphql:"... on JiraConfigurationOptions"` EmailConfigurationOptions EmailConfigurationOptions `graphql:"... on EmailConfigurationOptions"` GitlabConfigurationOptions GitlabConfigurationOptions `graphql:"... on GitlabConfigurationOptions"` // Add other configuration options here diff --git a/internal/provider/integration_jira_resource.go b/internal/provider/integration_jira_resource.go new file mode 100644 index 0000000..6455a79 --- /dev/null +++ b/internal/provider/integration_jira_resource.go @@ -0,0 +1,295 @@ +package provider + +import ( + "context" + "fmt" + "regexp" + + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + mondoov1 "go.mondoo.com/mondoo-go" +) + +var _ resource.Resource = (*integrationJiraResource)(nil) + +func NewIntegrationJiraResource() resource.Resource { + return &integrationJiraResource{} +} + +type integrationJiraResource struct { + client *ExtendedGqlClient +} + +type integrationJiraResourceModel struct { + SpaceID types.String `tfsdk:"space_id"` + + // integration details + Mrn types.String `tfsdk:"mrn"` + Name types.String `tfsdk:"name"` + Host types.String `tfsdk:"host"` + Email types.String `tfsdk:"email"` + + // Optional settings + DefaultProject types.String `tfsdk:"default_project"` + AutoCreate types.Bool `tfsdk:"auto_create"` + AutoClose types.Bool `tfsdk:"auto_close"` + + // credentials + Credential *integrationJiraCredentialModel `tfsdk:"credentials"` +} + +type integrationJiraCredentialModel struct { + Token types.String `tfsdk:"token"` +} + +func (r *integrationJiraResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_integration_jira" +} + +func (m integrationJiraResourceModel) GetConfigurationOptions() *mondoov1.JiraConfigurationOptionsInput { + opts := &mondoov1.JiraConfigurationOptionsInput{ + Host: mondoov1.String(m.Host.ValueString()), + Email: mondoov1.String(m.Email.ValueString()), + APIToken: mondoov1.String(m.Credential.Token.ValueString()), + DefaultProject: mondoov1.String(m.DefaultProject.ValueString()), + AutoCreateCases: mondoov1.NewBooleanPtr(mondoov1.Boolean(m.AutoCreate.ValueBool())), + AutoCloseTickets: mondoov1.NewBooleanPtr(mondoov1.Boolean(m.AutoClose.ValueBool())), + } + + return opts +} + +func (r *integrationJiraResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: `Integrate the Ticketing System Jira with Mondoo to automatically create and close issues based on Mondoo findings.`, + Attributes: map[string]schema.Attribute{ + "space_id": schema.StringAttribute{ + MarkdownDescription: "Mondoo Space Identifier. If it is not provided, the provider space is used.", + Optional: true, + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "mrn": schema.StringAttribute{ + Computed: true, + MarkdownDescription: "Integration identifier.", + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "Name of the integration.", + Required: true, + Validators: []validator.String{ + stringvalidator.LengthAtMost(250), + }, + }, + "host": schema.StringAttribute{ + MarkdownDescription: "Jira host URL.", + Required: true, + Validators: []validator.String{ + stringvalidator.RegexMatches( + regexp.MustCompile(`^https?:\/\/[a-zA-Z0-9\-._~:\/?#[\]@!$&'()*+,;=%]+$`), + "must be a valid URL", + ), + }, + }, + "email": schema.StringAttribute{ + MarkdownDescription: "Jira user email.", + Required: true, + Validators: []validator.String{ + stringvalidator.RegexMatches( + regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`), + "must be a valid email", + ), + }, + }, + "default_project": schema.StringAttribute{ + MarkdownDescription: "Default Jira project (is represented by the project key e.g. `MONDOO`).", + Optional: true, + }, + "auto_create": schema.BoolAttribute{ + MarkdownDescription: "Automatically create Jira issues for Mondoo findings.", + Optional: true, + }, + "auto_close": schema.BoolAttribute{ + MarkdownDescription: "Automatically close Jira issues for resolved Mondoo findings", + Optional: true, + }, + "credentials": schema.SingleNestedAttribute{ + Required: true, + Attributes: map[string]schema.Attribute{ + "token": schema.StringAttribute{ + MarkdownDescription: "Jira API token.", + Required: true, + Sensitive: true, + }, + }, + }, + }, + } +} + +func (r *integrationJiraResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(*ExtendedGqlClient) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *http.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + r.client = client +} + +func (r *integrationJiraResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data integrationJiraResourceModel + + // Read Terraform plan data into the model + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + // Compute and validate the space + space, err := r.client.ComputeSpace(data.SpaceID) + if err != nil { + resp.Diagnostics.AddError("Invalid Configuration", err.Error()) + return + } + ctx = tflog.SetField(ctx, "space_mrn", space.MRN()) + + // Do GraphQL request to API to create the resource. + tflog.Debug(ctx, "Creating integration") + integration, err := r.client.CreateIntegration(ctx, + space.MRN(), + data.Name.ValueString(), + mondoov1.ClientIntegrationTypeTicketSystemJira, + mondoov1.ClientIntegrationConfigurationInput{ + JiraConfigurationOptions: data.GetConfigurationOptions(), + }) + if err != nil { + resp.Diagnostics. + AddError("Client Error", + fmt.Sprintf("Unable to create Jira integration, got error: %s", err), + ) + return + } + + // Save space mrn into the Terraform state. + data.Mrn = types.StringValue(string(integration.Mrn)) + data.Name = types.StringValue(string(integration.Name)) + data.SpaceID = types.StringValue(space.ID()) + + // Save data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *integrationJiraResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data integrationJiraResourceModel + + // Read Terraform prior state data into the model + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + // Read API call logic + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *integrationJiraResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var data integrationJiraResourceModel + + // Read Terraform plan data into the model + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + // Do GraphQL request to API to update the resource. + opts := mondoov1.ClientIntegrationConfigurationInput{ + JiraConfigurationOptions: data.GetConfigurationOptions(), + } + + _, err := r.client.UpdateIntegration(ctx, + data.Mrn.ValueString(), + data.Name.ValueString(), + mondoov1.ClientIntegrationTypeTicketSystemJira, + opts, + ) + if err != nil { + resp.Diagnostics. + AddError("Client Error", + fmt.Sprintf("Unable to update Jira integration, got error: %s", err), + ) + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *integrationJiraResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data integrationJiraResourceModel + + // Read Terraform prior state data into the model + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + // Do GraphQL request to API to update the resource. + _, err := r.client.DeleteIntegration(ctx, data.Mrn.ValueString()) + if err != nil { + resp.Diagnostics. + AddError("Client Error", + fmt.Sprintf("Unable to delete Jira integration, got error: %s", err), + ) + return + } +} + +func (r *integrationJiraResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + integration, ok := r.client.ImportIntegration(ctx, req, resp) + if !ok { + return + } + + model := integrationJiraResourceModel{ + Mrn: types.StringValue(integration.Mrn), + Name: types.StringValue(integration.Name), + SpaceID: types.StringValue(integration.SpaceID()), + Host: types.StringValue(integration.ConfigurationOptions.JiraConfigurationOptions.Host), + Email: types.StringValue(integration.ConfigurationOptions.JiraConfigurationOptions.Email), + DefaultProject: types.StringValue(integration.ConfigurationOptions.JiraConfigurationOptions.DefaultProject), + AutoCreate: types.BoolValue(integration.ConfigurationOptions.JiraConfigurationOptions.AutoCreateCases), + AutoClose: types.BoolValue(integration.ConfigurationOptions.JiraConfigurationOptions.AutoCloseTickets), + Credential: &integrationJiraCredentialModel{ + Token: types.StringPointerValue(nil), + }, + } + + resp.State.Set(ctx, &model) +} diff --git a/internal/provider/integration_jira_resource_test.go b/internal/provider/integration_jira_resource_test.go new file mode 100644 index 0000000..c30cb3c --- /dev/null +++ b/internal/provider/integration_jira_resource_test.go @@ -0,0 +1,103 @@ +// Copyright (c) Mondoo, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +package provider + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +func TestAccJiraResource(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + // Create and Read testing + { + Config: testAccJiraResourceConfig(accSpace.ID(), "one", "https://your-instance.atlassian.net", "jira.owner@email.com", "MONDOO"), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "name", "one"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "space_id", accSpace.ID()), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "host", "https://your-instance.atlassian.net"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "email", "jira.owner@email.com"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "default_project", "MONDOO"), + ), + }, + { + Config: testAccJiraResourceWithSpaceInProviderConfig(accSpace.ID(), "two", "abctoken12345", true, false), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "name", "two"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "space_id", accSpace.ID()), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "credentials.token", "abctoken12345"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "auto_create", "true"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "auto_close", "false"), + ), + }, + // Update and Read testing + { + Config: testAccJiraResourceConfig(accSpace.ID(), "one", "https://your-instance.atlassian.net", "jira.owner@email.com", "MONDOO"), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "name", "one"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "space_id", accSpace.ID()), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "host", "https://your-instance.atlassian.net"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "email", "jira.owner@email.com"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "default_project", "MONDOO"), + ), + }, + { + Config: testAccJiraResourceWithSpaceInProviderConfig(accSpace.ID(), "two", "abctoken12345", false, true), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "name", "two"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "space_id", accSpace.ID()), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "credentials.token", "abctoken12345"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "auto_create", "false"), + resource.TestCheckResourceAttr("mondoo_integration_jira.test", "auto_close", "true"), + ), + }, + // Delete testing automatically occurs in TestCase + }, + }) +} + +func testAccJiraResourceConfig(spaceID, intName, host, email, defaultProject string) string { + return fmt.Sprintf(` +resource "mondoo_integration_jira" "test" { + space_id = %[1]q + name = %[2]q + host = %[3]q + email = %[4]q + default_project = %[5]q + + auto_create = true + auto_close = true + + credentials = { + token = "abcd1234567890" + } +} +`, spaceID, intName, host, email, defaultProject) +} + +func testAccJiraResourceWithSpaceInProviderConfig(spaceID, intName, token string, autoCreate, autoClose bool) string { + return fmt.Sprintf(` +provider "mondoo" { + space = %[1]q +} +resource "mondoo_integration_jira" "test" { + name = %[2]q + host = "https://your-instance.atlassian.net" + email = "jira.owner@email.com" + default_project = "MONDOO" + + auto_create = %[4]t + auto_close = %[5]t + + credentials = { + token = %[3]q + } +} +`, spaceID, intName, token, autoCreate, autoClose) +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 4995328..bbb21dc 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -204,6 +204,7 @@ func (p *MondooProvider) Resources(ctx context.Context) []func() resource.Resour NewIntegrationShodanResource, NewFrameworkAssignmentResource, NewCustomFrameworkResource, + NewIntegrationJiraResource, NewIntegrationEmailResource, NewIntegrationGitlabResource, }